2016-07-07 69 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); 
    } 
}