2016-09-14 61 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

你已经理解了,虽然我的东西已经少了一些锅炉板代码和更通用的东西,但我很感谢你的加入。 –