Add related entities if it doesn't exists
I have 2 entities that are related to each other via an intermediate
table. The Product entity has a unique constraint on the Name set. These
are the POCO classes:
public class User
{
public string Name { get; set; }
public string LastName { get; set; }
public string AnotherProp { get; set; }
}
public class Product
{
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
}
The Intermediate table is called UserProduct
I'm trying to meet these conditions:
If a User adds a Product, a check in the database for existence should
take place first and if exist add a reference in the intermediate table.
If it doesn't exists create the Product and add a reference to User
If the Product list that comes back from a submit and doesn't contain the
products that where initially referenced to this User in the database, the
reference should be removed, and if no other User has a reference to this
Product either, the Product should be removed as well.
Avoid database calls like checking every single Product etc.
I can only think of doing this with a few loops and maintaining a few
lists, which I find to be very ugly and mistakes are easily made. Is there
any efficient way of doing this?
Does EntityFramework have something for this I missed?
No comments:
Post a Comment