使用Entity Framework更新多对多关系

时间:2015-05-21 13:10:46

标签: entity-framework

我正在使用Entity Framework进行多对多关系更新。我的表看起来像这样:

CREATE TABLE Agreement
(
    ID int NOT NULL IDENTITY(1,1),
    CONSTRAINT [PK_Agreement] PRIMARY KEY CLUSTERED (ID),
);

CREATE TABLE Price
(
    ID int NOT NULL IDENTITY(1,1),  
    ProductPrice decimal(18,5),
    CONSTRAINT [PK_Price] PRIMARY KEY CLUSTERED (ID),
);

CREATE TABLE AgreementPriceLine
(
    AgreementID int NOT NULL,   
    PriceID int NOT NULL,
    CONSTRAINT [PK_AgreementPriceLine] PRIMARY KEY NONCLUSTERED (AgreementID, PriceID), 
    CONSTRAINT [FK_AgreementPriceLine_Agreement]
    FOREIGN KEY (AgreementID) REFERENCES Agreement (ID)
    ON DELETE NO ACTION ON UPDATE CASCADE,
    CONSTRAINT [FK_AgreementPriceLine_PriceID]
    FOREIGN KEY (PriceID) REFERENCES Price (ID) 
); 

哪个实体框架如此映射(使用数据库中的生成模型,.edmx文件):

public partial class Agreement
{
    public Agreement()
    {
        this.Prices = new HashSet<Price>();
    }

    public virtual ICollection<Price> Prices { get; set; }
}

public partial class Price
{
    public Price()
    {
        this.Agreements = new HashSet<Agreement>();
    }

    public virtual ICollection<Agreement> Agreements { get; set; }
}

现在,如果我想更新协议的两个价格,我该如何处理?我尝试了以下方法:

    public void UpdateAgreementPriceLines(List<Price> prices, Agreement agreement)
    {
        try
        {
            using (var ctx = new MyEntities())
            {
                if (agreement != null)
                {
                    // Make sure the number of prices are equal before attempting to "update" anything
                    if(agreement.Prices.Count == prices.Count)
                    { 
                        // Clear old prices
                        agreement.Prices.Clear();

                        // Add new prices
                        foreach (var price in prices)
                        {                                
                            agreement.Prices.Add(price);
                        }

                        ctx.SaveChanges();
                    }

                }
            }
        }
        catch (Exception e)
        {
            Logging.Instance.Fatal(e.ToString());
        }
    }

但它相当&#39; hacky&#39;首先清空集合,然后添加新价格。此外,我无法让它工作,价格根本没有删除/添加(并没有被捕获的例外)

非常感谢任何帮助/暗示: - )

提前致谢。

1 个答案:

答案 0 :(得分:0)

您需要从集合中删除项目,如下所示:

agreement.Prices.Remove(priceItem);

要删除所有对象,您可以执行以下操作:

var prices = agreement.Prices.ToList();
agreement.Prices.RemoveRange(prices);

如果您不想在删除方法之前将所有项目加载到内存中,则可以执行以下操作:

//supposing that you want to deleted the Price which id = 10

Price deletedPrice = new Price { PriceId = 10 };  
Context.Entry(deletedPrice).State = EntityState.Deleted;  
Context.SaveChanges();