2016-09-14 63 views
1

我正在使用將xml反序列化爲用於構建實際EF數據模型的模型實例的web服務。更新或插入導航屬性

如果我有這樣的例子類建模PropertyBranch

public class Property 
{ 
    public int Id {get; set;} 

    public int Name {get; set;} 

    public string BranchId {get; set;} 

    [ForeignKey("BranchId")] 
    public string Branch {get; set;} 
} 

如果Branch不存在於數據庫中,細,EF將其插入。但是,如果是這樣,我該如何指示EF來更新它呢?

我從例子中得到一個實體到DbSet,以便框架知道不要插入它,但有沒有辦法做到這一點自動神奇?例如不必寫每個我插入一個Property檢查Branch bolierplate代碼,知道我是否需要Attach()它?

+1

你所描述的是一個Upsert。我認爲這是一個重複的問題。我會標記它並在那裏提供鏈接。 – Necoras

+1

現在,如果我知道它被標記爲'Upsert',我可能會發現沒有發佈的答案!感謝您的鏈接,非常有幫助。 –

回答

1
public Task Upsert(Property property) 
{ 
    using (var context = new SomeDbContext()) 
    { 
     //if the id is autoincrement field then you will need to pass the new id to the property if it changes. 
     await Save(new Branch{ Id = property.BranchId, Name = property.Branch}, context); 
     await Save(property, context); 
     await context.SaveChangesAsync(); 
    } 
} 
private Task Save(Property property, SomeDbContext context) 
{ 
    var existingProperty = context.Property.FirstOrDefaultAsync(f => f.Id == property.Id); 
    if (existingProperty == null) 
    { 
     context.Property.Add(property); 
    } 
    else 
    { 
     //maybe use automapper here if there is a lot of this stuff going on 
     //EF is smart enough to figure out what needs updating and will write a terse update statment 
     //no attach is needed since your existingProperty still exist within your context 
     existingProperty.Name = property.Name; 
     existingProperty.BranchId = property.BranchId; 
     existingProperty.Branch = property.Branch; 
    } 

} 
private Task Save(Branch branch, SomeDbContext context) 
{ 

    var existingBranch = context.Branch.FirstOrDefaultAsync(f => f.Id == branch.Id); 
    if (existingBranch == null) 
    { 
     context.Branch.Add(branch); 
    } 
    else 
    { 
     existingBranch.Name = branch.Name; 
    } 
} 

我希望我已經理解了你的問題......這是我猜想很多方法之一。這裏的好處是你的更新語句被EF優化,所以如果只有「名稱」或「分支」發生改變,那麼它只會更新這些字段。無論如何 - 我希望這有助於。

+0

你已經理解了,雖然我的東西已經少了一些鍋爐板代碼和更通用的東西,但我很感謝你的加入。 –