簡體   English   中英

帶附件的實體框架更新不起作用

[英]Entity Framework Update with Attach not works

我有一堂課

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

並且只有客戶端有效,但地址無法更新。 如何使用?

可能有幫助

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