首页 > 解决方案 > 为什么内部模型没有更新

问题描述

我有 3 个模型要更新

public class ProductModel
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ProductId { get; set; }
    
    public int BrandId { get; set; }
    [ForeignKey("BrandId")]
    public virtual BrandModel Brand { get; set; }

    public virtual PackModel Pack { get; set; }
}

public class BrandModel
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int BrandId { get; set; }
    public string BrandName { get; set; }
    [JsonIgnore]
    public virtual ProductModel Product { get; set; }
    public int PackWidth { get; set; }
}

public class PackModel
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int PackId { get; set; }

    public int ProductId { get; set; }
    [JsonIgnore]
    public virtual ProductModel Product { get; set; }
}

数据库具有所有键的身份规范 ( 在此处输入图像描述)

我使用 UnitOfWork:

public class UnitOfWork : IUnitOfWork
    {
        private readonly ApplicationContext _context;
        public UnitOfWork(ApplicationContext context)
        {
            _context = context;
            BrandRepository = new BrandRepositories(_context);
            ProductRepository = new ProductRepositories(_context);
        }
        public IBrandRepositories BrandRepository { get; private set; }
        public IProductRepositories ProductRepository { get; private set; }
        public int Complete()
        {
            return _context.SaveChanges();
        }
        public void Dispose()
        {
            _context.Dispose();
        }
    }

和通用存储库:

public interface IProductRepositories : IGenericRepository<ProductModel>
    {
    }

public interface IGenericRepository<T> where T : class
    {
        Task<T> UpdateAsyn(T t, object key);
    }

我的背景

public class ApplicationContext : DbContext
{
    public ApplicationContext(DbContextOptions<ApplicationContext> options) : base(options)
    {
    }
    public DbSet<BrandModel> Brand { get; set; }
    public DbSet<ProductModel> Product { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<BrandModel>().ToTable("Brand").HasKey(k=>k.BrandId);
        modelBuilder.Entity<BrandModel>().Property(p => p.BrandId).IsRequired().HasMaxLength(30).ValueGeneratedOnAdd();

        modelBuilder.Entity<ProductModel>()
            .HasOne<BrandModel>(p => p.Brand)
            .WithOne(b => b.Product)
            .HasForeignKey<ProductModel>(pr => pr.BrandId);
        modelBuilder.Entity<ProductModel>().ToTable("Product").HasKey(k => k.ProductId);
        modelBuilder.Entity<ProductModel>().Property(p => p.ProductId).IsRequired().ValueGeneratedOnAdd();

        modelBuilder.Entity<ProductModel>()
            .HasOne<PackModel>(a => a.Pack)
            .WithOne(b => b.Product)
            .HasForeignKey<PackModel>(b => b.ProductId);

        modelBuilder.Entity<PackModel>().ToTable("Pack").HasKey(k => k.PackId);
    }
}

我想用品牌和包装更新产品。然后我做简单的方法

public virtual async Task<T> UpdateAsyn(T t, object key)
        {
            if (t == null)
                return null;
            T exist = await _context.Set<T>().FindAsync(key);
            _context.Entry(exist).State = EntityState.Detached;
            if (exist != null)
            {
                try
                {
                    _context.Entry(exist).CurrentValues.SetValues(t);
                    await _context.SaveChangesAsync();
                }
                catch (Exception e)
                {
                    _logger.Error($"GenericRepository:UpdateAsyn >>> Message: {e.Message}, StackTrace: {e.StackTrace}");
                    throw;
                }
                
            }
            return exist;
        }

运行 SaveChangesAsync() 时,我只更新产品模型,我可以更改 BrandId 但是当我更改 PackModel 中的某些内容(PackWidth 或其他...)时,它不会改变。

我正在使用分离的实体,但不适用于我

为什么它不更新嵌套模型?

标签: .net-coreentity-framework-core

解决方案


我相信这是错误的:

_context.Entry(exist).State = EntityState.Detached;

因为你脱离exist_context.

然后

_context.Entry(exist).CurrentValues.SetValues(t);

这意味着“使用”exist的所有属性更新属性t。这将更新 this 的所有属性exist,尽管它不再附加。

所以,

await _context.SaveChangesAsync();

不会保存任何东西。

请重试,删除分离您读取的实体的行。

如果我误解了你的问题是什么,请告诉我。


推荐阅读