简体   繁体   English

使用实体框架代码优先方法,如何创建一个具有相关实体列表作为子属性的实体?

[英]Using Entity Framework Code First approach, how do I create an entity that has a list of related entities as a child property?

SOLVED!!! 解决了!!!

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;
        }

Original Post 原始帖子

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: 这是我的两个域模型:

Order 订购

 [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; }
        }
    }

Product 产品

[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":[]}]
}

Expected Behavior 预期行为

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. 当我POSTOrder对象到服务器,我本来期望的是创建一个新的秩序,属于该订单的产品只会被引用。

Encountered Behavior 遇到的行为

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): 这是我的“产品”表最终的外观(请注意重复的产品):

在此处输入图片说明

UPDATE 更新

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. 提前致谢。

UPDATE #1: 更新#1:

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.

相关问题 如何使用实体框架代码优先方法正确创建数据库 - How to correctly create a database using entity framework code first approach 首先使用Entity Framework代码将2个相关实体合并到1个表中 - 2 related entities into 1 table using Entity Framework code first 如何通过实体框架代码优先方法定义导航属性 - How to define a navigation property via Entity Framework code first approach 在实体框架中,如何在代码中创建关联属性? - In Entity Framework, how do I create an Association Property in code? 实体框架:创建一个实体,附加子实体,做一些事情然后保留实体……如何? - Entity Framework: Create an entity, attach child entities, do some stuff then persist entities… how? 如何使用Entity Framework Core 2.0为X实体创建链接的X实体 - How do I create linked X entities for a X entity using Entity Framework Core 2.0 如何使用Entity Framework 7在代码中首先处理这两个模型? - How handle these two models in code first approach using Entity Framework 7? 如何使用实体框架从数据库视图加载相关实体? - How do I load related entities from a database view using entity framework? 如何使用实体框架 6 代码优先方法在 SQL Server 中创建序列并应用两个表? - How to create the sequence and apply two tables in SQL Server using Entity framework 6 code first approach? 如何使用实体框架将项目添加到列表属性 - How do i add items to a list property using Entity Framework
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM