我有一个类
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) 它运行良好,我的客户端和地址保留在数据库中。
但是当我需要更新不起作用时我使用
public virtual TEntity Atualizar(TEntity obj)
{
var entry = Db.Entry(obj);
DbSet.Attach(obj);
entry.State = EntityState.Modified;
return obj;
}
并且只有客户端有效,但地址不更新。怎么用这个?
这可能会有所帮助
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);
}
}