简体   繁体   English

多对多插入或更新实体框架

[英]Insert or Update Entity Framework Many-to-Many

I am trying to update a join table using Entity Framework that has the following design 我正在尝试使用具有以下设计的实体框架更新联接表 在此处输入图片说明

I am trying the following piece of code but it doesn't update the join table DeliveryDayBrands, please tell me what I am doing wrong. 我正在尝试以下代码,但它不会更新联接表DeliveryDayBrands,请告诉我我做错了什么。 Thanks. 谢谢。

public async Task<Brand> Update(Brand brand, IEnumerable<int> SelectedDeliveryDays)
    {

        using (var dc = DataContext())
        {
            foreach (int deliveryDayId in SelectedDeliveryDays)
            {
                DeliveryDay deliveryDay = new DeliveryDay();
                deliveryDay = dc.DeliveryDays.FirstOrDefault(d => d.DeliveryDayId == deliveryDayId);


                brand.DeliveryDays.Add(deliveryDay);

            }

            dc.SetModified(brand);
            await dc.SaveChangesAsync();
            return brand;
        }
    }

It looks like you're trying to add some already existing DeliveryDays to a Brand. 您似乎正在尝试向品牌中添加一些已经存在的DeliveryDay。 You don't need to re-add it to the database, as doing so will result in creating duplicates. 您无需将其重新添加到数据库中,因为这样做将导致创建重复项。

Also, as described in this answer , DataContext is used for LINQ to SQL. 另外,如本答案所述DataContext用于LINQ to SQL。 The answer says you need to use the DbContext class to talk to Entity Framework. 答案表明您需要使用DbContext类与Entity Framework进行对话。

I suggest you try to fetch the connection string to the database from your web.config (or elsewhere), and then try the following: 我建议您尝试从web.config (或其他位置)中获取到数据库的连接字符串,然后尝试以下操作:

public async Task<Brand> Update(Brand brand, IEnumerable<int> SelectedDeliveryDays)
{
    using (var context = new DbContext([insert connectionString to database here]))
    {
        foreach (int deliveryDayId in SelectedDeliveryDays)
        {
            DeliveryDay deliveryDay = context.DeliveryDays.FirstOrDefault(
               d => d.DeliveryDayId == deliveryDayId);

            deliveryDay.Brands.Add(brand);
            brand.DeliveryDays.Add(deliveryDay)

            // You could also use your custom SetModified method.
            context.Entry(brand).State = EntityState.Modified;
            context.Entry(deliveryDay).State = EntityState.Modified;
        }            

        await context.SaveChangesAsync();
        return brand;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM