具有映射表的实体框架添加重复条目

时间:2014-06-23 15:46:48

标签: entity-framework ef-code-first

我有两个表客户和具有多对多关系的产品,我使用名为customerproductmap的映射表处理这些关系。然后我从这个数据库创建了实体框架模型。

这就是我为客户提供的onmodelcreation:

modelBuilder.Entity<customer>()
            .HasMany(e => e.products)
            .WithMany(e => e.customers)
            .Map(m => m.ToTable("customerproductMap").MapLeftKey("customerId").MapRightKey("productId"));

当我使用Context添加新数据时,我发现正在向客户添加重复的条目。我从客户端获得的json数据具有多个客户的父对象。每个客户都可以映射多个产品,但这些产品可能已由前一个客户添加。对于例如customer1-&GT; products1和product2 and customer2-&gt; Product1。这导致两次添加Product1,然后将这些映射到映射表中。

我想要的是Product1只添加一次,然后映射到customer1和customer2,因为它是同一个产品。我怎样才能做到这一点?

using (var context = new DbEntity())
        {
            context.ParentObject.Add(GetEntityFromClientData((clientdata)));
            try
            {
                context.SaveChanges();
            }
            catch (DbEntityValidationException e)
            {
                .. processing of exception message
           }
        }

我是实体框架的新手,所以我可能很遗憾。

修改 以下是GetEntityFromClientData的作用(相关部分)。您看到我将product1和product2映射到customer1,将product1映射到customer2。然后将该区域添加到数据库。如果我不这样做,我将如何将customer2映射到product1。

var customers = new List<Customer>();
        foreach (var clientCustomer in clientData.Customers)
        {
            var q = from o in clientCustomer.Products
                    select new Product()
                    {
                        ..basic initialization,
                    };

            var customer = new Customer()
            {
                Name = clientCustomer.Name,
                Products = q.ToArray(),
                CustomerId = clientCustomer.Id,
            };

            customers.Add(customer);
        }

        var customerLocation = new CustomerLocation ()
        {
            city = clientData.City,
            Customers= customers.ToArray(),
        };

        var customerLocations = new CustomerLocation []
        {
            customerLocation
        };

        var region = new Region()
        {
            CustomerLocations = customerLocations,
        };

        return region; 

0 个答案:

没有答案
相关问题