简体   繁体   English

带附件的实体框架更新不起作用

[英]Entity Framework Update with Attach not works

I have a class 我有一堂课

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; }
}

when i add Client in my generic repository i only use DbSet.Add(obj) it works well, my client and address persist in DB. 当我在通用存储库中添加客户端时,我仅使用DbSet.Add(obj)即可正常工作,我的客户端和地址仍保留在DB中。

but when i need to update not works i use 但是当我需要更新时我无法使用

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

and only client works, but address not update. 并且只有客户端有效,但地址无法更新。 How use this? 如何使用?

It might help 可能有帮助

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);
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM