2016-07-07 60 views
0

我有一个类实体框架更新与安装不工作

public class Client 
{ 
    public int ClientId {get;set;} 
    public string Name {get;set;} 
    public virtual ICollection<Address> Addresses{ get; set; } 
} 

public class Address 
{ 
    public int AdressId {get;set;} 
    public string Street {get;set;} 
    public int ClientId { get; set; } 
} 

当我在通用存储库中添加客户端我只用 DbSet.Add(OBJ)它工作得很好,我的客户和地址在DB坚持。

但是当我需要更新不工作 我使用

public virtual TEntity Atualizar(TEntity obj) 
{ 
    var entry = Db.Entry(obj); 
    DbSet.Attach(obj); 
    entry.State = EntityState.Modified; 
    return obj; 
} 

,只有客户端的工作,但地址不会更新。 如何使用此?

+1

你不保存您的上下文。而且,你有附加你的实体吗? –

+2

您需要遍历整个图形,并将“地址”项目标记为已修改。 EF认为它们默认保持不变。 – Dennis

回答

0

这可能有助于

using System.Data.Entity; 
using System.Collections.Generic; 
using System.ComponentModel.DataAnnotations; 
using System.ComponentModel.DataAnnotations.Schema; 

public interface IEntity 
{ 
} 

public class Address : IEntity 
{ 
    [Key] 
    public int AddressId { get; set; } 
    public string Street { get; set; } 
    [ForeignKey("Client")] 
    public int ClientId { get; set; } 
    public Client Client { get; set; } 
} 

public class Client : IEntity 
{ 
    [Key] 
    public int ClientId { get; set; } 
    public string Name { get; set; } 
    public virtual ICollection<Address> Addresses { get; set; } 
} 

public class GenericRepo<T> where T : class, IEntity 
{ 
    private ClientsDbContext context; 
    public GenericRepo(ClientsDbContext context) 
    { 
     this.context = context; 
    } 
    public virtual void Update(T entity) 
    { 
     context.Set<T>().Attach(entity); 
     context.Entry(entity).State = EntityState.Modified; 
     context.SaveChanges(); 
    } 

    public virtual void Add(T entity) => context.Set<T>().Add(entity); 
    public virtual T Get(int id) => context.Set<T>().Find(id); 
    public virtual void SaveContext() => context.SaveChanges(); 
} 
class Program 
{ 
    static void Main(string[] args) 
    { 
     var clientRepo = new GenericRepo<Client>(new ClientsDbContext()); 
     var client = new Client { Addresses = new List<Address> { new Address { Street = "some street" } }, Name = "ClienName" }; 

     clientRepo.Add(client); 
     clientRepo.SaveContext(); 

     // than update already existing entity, by adding new addresses 
     var dbClient = clientRepo.Get(client.ClientId); 
     dbClient.Addresses.Add(new Address { Street = "New street 1" }); 
     dbClient.Addresses.Add(new Address { Street = "New street 2" }); 
     clientRepo.Update(client); 
    } 
}