Reputation: 143
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.
Upvotes: 1
Views: 992
Reputation: 2812
I struggled with this a lot in the past. At the time and as far as I know, there's not a way to say to EF, "this nested object may or may not be in the table. If it's primary key is already there, don't try to insert it again".
The workaround was to do this:
someentity.Product = _context.Products.SingleOrDefault(p => p.Id == someEntity.Product.Id) ?? someentity.Product;
_context.Entities.Add(someentity);
_context.SaveChanges();
If you set the value from the database then it knows it's the exact same object and will not try to add it in.
Upvotes: 1