I have a model Product with a 1:n relationship with model Product_Tag. I also have a model Tag has a 1:n relationship with Product_Tag.
class Product{
int ID {get;set;}
public virtual ICollection<Product_Tag> productTag {get;set;}
}
class Tag {
int ID {get;set;}
public virtual ICollection<Product_Tag> productTag {get;set;}
}
class Product_Tag {
int ID {get;set;}
int ProductID{get;set;}
int TagID {get;set;}
public virtual Product product {get;set;}
public virtual Tag tag {get;set;}
}
When saving a new Product, I want to be able to save any associations to Tags in Product_Tags. Product_Tag requires a PRoductID and a TagID. I have the TagID’s available at save time, but the ProductID will come from thew newly-created Product. How to get the newly-created Product’s ID immediately after saving the new Product?
Alternatively, is there a way to just save the Product model with its productTags having only TagID’s and get DbContext to fill in the ProductID for me?
When you add a new entity to the database, its ID will be automatically populated by Entity Framework. You can use it.
Also, EF can work with ‘many-to-many’ relationships, and you don’t need to create additional class for relationship itself. If you use code first, you can use this mapping:
Then, you can do something like this:
In this case EF automatically creates a new product, two tags and two relationships between created product and tags.