Reputation: 7555
I am using EF CodeFirst
approach for quite long. This is how I used to define one to many relationship.
//one Customer can have many products --> One to Many relationship.
public class Customer
{
[Key]
public int CustId { get; set; }
public string CustName { get; set; }
public virtual List<Product> Products { get; set; }
}
public class Product
{
[Key]
public int ProdId { get; set; }
public string BuyDate { get; set; }
[ForeignKey("Customer")]
public int CustomerId { get; set; }
public virtual Customer Customer { get; set; }
}
But recently while one discussion, I came to know that this is not the best approach. There is a way where I can define such relationship without overhead of public int CustomerId { get; set; }
in Product Entity.
How do I do this?
Upvotes: 1
Views: 986
Reputation: 2585
When you define the relationship as following it should be enough to create a one-to-many relationship between product and customer
public class Customer
{
//other properties omitted
public virtual ICollection<Product> Products { get; set; }
}
public class Product
{
//other properties omitted
[ForeignKey("Customer")]
public int CustomerId { get; set; }
public virtual Customer Customer { get; set; }
}
In EF you can then set this relationship (for a new product) in the following ways:
var customer = context.Customers.GetById(1);
var myProduct = new Product()
{
//set all the properties
}
customer.Products.Add(myProduct);
context.SaveChanges();
When you have loaded a product with EF, you can acces the customer (and all its properties) just by navigating to it:
string name = myProduct.Customer.CustName;
int custId = myProduct.Customer.Id;
note that querying the products dbset and looking at the customerId causes the generated SQL to perform a join to the customers table which can have a negative effect on performance.
I don't find your example to be a bad solution. I think that in some cases it makes sense to include the CustomerId in your model (it is created in the database anyway by EF to create the relationship).
Upvotes: 1
Reputation: 4350
Just leave out the CustomerId
property from Product
, and rename the primary key in Customer
to CustomerId
.
Upvotes: 0