1

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.

6
  • Adding AsNoTracking() would make it worse. EF must know that it is an already existing entity. Commented Apr 28, 2021 at 20:03
  • Does your Entity class has a property for the foreign key of the Products entity? Commented Apr 28, 2021 at 20:05
  • I could add the public int ProductId property to your entity class.. I am not sure how .net is handling that implicit relation between product and entity.. Commented Apr 28, 2021 at 20:10
  • Please edit your question to include a minimal reproducible example, which generates the exception when executed. Commented Apr 28, 2021 at 20:45
  • Progman foreign key exist. Rolando I can public int ProductId but then i cant use Include() Commented Apr 29, 2021 at 7:11

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.