[英]Using Entity Framework Code First approach, how do I create an entity that has a list of related entities as a child property?
Thanks to comments made by Gert below, I was able to solve. 感谢下面Gert的评论,我得以解决。 I simply needed to attach my Product
entities to the same context as the Order
entity before saving the order: 我只需要在保存Order
之前将我的Product
实体附加到与Order
实体相同的上下文中:
public int Create(Order entity)
{
var order = entity;
foreach (var product in order.Products)
{
db.Products.Attach(product);
}
db.Orders.Add(order);
db.SaveChanges();
return order.Id;
}
Thanks for looking. 感谢您的光临。 Here is my use case: 这是我的用例:
On an ecommerce application, I need to create an Order
. 在电子商务应用程序上,我需要创建一个Order
。 The Order
has one or many Product
entities as one of its properties. Order
具有一个或多个Product
实体作为其属性之一。 Here are my two domain models: 这是我的两个域模型:
[Table("Order")]
public class Order
{
[Required(ErrorMessage = "Please enter a description.")]
public string Description { get; set; }
[Required(ErrorMessage = "Please enter a trackingnumber.")]
public string TrackingNumber { get; set; }
[Key]
public int Id { get; set; }
[Required(ErrorMessage = "Please enter an isactive.")]
public bool IsActive { get; set; }
public int UserId { get; set; }
public virtual User User { get; set; }
public int OrderStatusTypeId { get; set; }
public virtual OrderStatusType OrderStatusType { get; set; }
private ICollection<Product> _products;
public virtual ICollection<Product> Products
{
get { return _products ?? (_products = new Collection<Product>()); }
set { _products = value; }
}
}
[Table("Product")]
public class Product
{
[Required(ErrorMessage = "Please enter a description.")]
public string Description { get; set; }
[Key]
public int Id { get; set; }
[Required(ErrorMessage = "Please enter a name.")]
public string Name { get; set; }
private ICollection<Order> _orders;
public virtual ICollection<Order> Orders
{
get { return _orders ?? (_orders = new Collection<Order>()); }
set { _orders = value; }
}
private ICollection<DeviceModel> _devicemodels;
public virtual ICollection<DeviceModel> DeviceModels
{
get { return _devicemodels ?? (_devicemodels = new Collection<DeviceModel>()); }
set { _devicemodels = value; }
}
}
Here is a look at a post object that the user has created: 这是用户创建的post对象的外观:
{
"Description": "Test description",
"TrackingNumber": "12345",
"Id": 1,
"IsActive": true,
"UserId": 0,
"User": {
"Email": "john@gmail.com",
"FirstName": "John",
"Id": 1,
"LastName": "Doe"
},
"OrderStatusTypeId": 0,
"OrderStatusType": {
"Description": "The order is in processing.",
"Id": 1,
"Title": "Processing"
},
"Products": [{"Description":"Test product","Id":1,"Name":"Product A","DeviceModels":[]},{"Description":"Test","Id":2,"Name":"Product B","DeviceModels":[]}]
}
When I POST
this Order
object to the server, I would have expected that a new order is created and the products belonging to that order would simply be referenced. 当我POST
此Order
对象到服务器,我本来期望的是创建一个新的秩序,属于该订单的产品只会被引用。
Each time I place an order, the related products are added a new products to the product table. 每次下订单时,相关产品都会在产品表中添加新产品。 So, rather than having a few products that are referenced by several orders, I have several products with 1-to-1 relationship with the orders. 因此,我有几个与订单具有一对一关系的产品,而不是几个订单引用了一些产品。
Here is what my Products table ends up looking like (note the repeated products): 这是我的“产品”表最终的外观(请注意重复的产品):
The Code First Approach DOES create a ProductOrders
conjunction table for me, and it even adds the order and product ids to that table: 代码优先方法确实为我创建了ProductOrders
联结表,甚至ProductOrders
表添加了订单和产品ID:
So why does it also add the products as new entities in the Product
table rather than simply referencing the keys I pass to it? 那么,为什么还要将产品作为新实体添加到“ Product
表中,而不是简单地引用我传递给它的键?
Thanks in advance. 提前致谢。
Here is my repository class for creating orders: 这是我用于创建订单的存储库类:
public class OrderRepository : IRepository<Order, int>
{
private readonly ApplicationDbContext db;
public OrderRepository(ApplicationDbContext dbContext)
{
db = dbContext;
}
/// <summary>
/// Creates and saves a new 'Order' entity.
/// </summary>
/// <param name="entity">The Order to save.</param>
/// <returns>The id (int) of the newly created Order.</returns>
public int Create(Order entity)
{
var order = entity;
db.Orders.Add(order);
db.SaveChanges();
return order.Id;
}
}
}
You will need to define the mappings for your collections. 您将需要为您的集合定义映射。 Here is an example using the fluent mapping interface. 这是使用流畅映射界面的示例。
public class OrderMapping: EntityTypeConfiguration<Order>
{
public OrderMapping()
{
HasMany(o => o.Products).WithMany(p => p.Orders).Map(m =>
{
m.MapLeftKey("OrderId");
m.MapRightKey("ProductId");
m.ToTable("Order_Products");
});
}
}
This will create a link table between Orders and Products. 这将在订单和产品之间创建一个链接表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.