I have these entities
[Table("Entity")]
public class Entity
{
public int Id { get; set; }
public Products Product { get; set; }
}
[Table("Products")]
public class Products
{
[Key]
public int Id { get; set; }
public string ProductName { get; set; }
public int Category { get; set; }
[NotMapped]
public string CategoryName { get; set; }
}
When I add a new entity to the database with this code:
_context.Entities.Add(someentity);
_context.SaveChanges();
Products product also try to add to database. But I don't want it because this entity already exists.
I tried to use AsNoTracking.
var product = _context.Product.AsNoTracking().Where(x=>x.ProductId == Id).FirstOrDefault();
var entity = new Entity{Id = 1, Product = product};
_context.Entity.Add(entity );
_context.SaveChanges();
and add virtual
public virtual Products Product { get; set; }
but it doesn't work.
AsNoTracking()would make it worse. EF must know that it is an already existing entity.Entityclass has a property for the foreign key of theProductsentity?