EFCore 通用存储库和 UnitOfWork 设计模式

问题描述

当我尝试创建新数据并保存它时,我在

public int Complete()
       {
           return _context.SaveChanges();
       }

错误告诉我: The value of 'Agency.ID' is unknown when attempting to save changes. This is because the property is also part of a foreign key for which the principal entity in the relationship is not known. .

我有一个这样的基类:

 public class Base
    {
        protected Base()
        {
            CreatedDate = DateTime.Now;
            IsDeleted = false;
            ModifiedDate = null;
        }

        public int ID { get; set; }
        public int? CreatedUserId { get; set; }
        public int? ModifiedUserId { get; set; }
        public string CreatedUserType { get; set; }
        public string ModifiedUserType { get; set; }
        public DateTime? CreatedDate { get; set; }
        public DateTime? ModifiedDate { get; set; }
        public bool? IsActive { get; set; }
        public bool? IsDeleted { get; set; }
    }

我有一个这样的代理类:

   public class Agency : Base
    {
        public Agency()
        {
            AgencyIsComplated = false;
        }
        [Required,StringLength(255)]
        public string AgencyName { get; set; }

        [Required,StringLength(255)]
        public string AgencyPhoto { get; set; }

        [Required,StringLength(255)]
        public string AgencyEMail { get; set; }

        [Required,StringLength(13)]
        public string AgencyPhone { get; set; }

        [StringLength(13)]
        public string AgencyBPhone { get; set; }

        [StringLength(255)]
        public string AgencyInfo { get; set; }

        [Required,StringLength(255)]
        public string AgencyTitle { get; set; }

        [Required,StringLength(255)]
        public string AgencyLink { get; set; }

        public int AgencyExportArea { get; set; } // Join table ile yapılacak,ayrı bir tabloda tutulacak

        [Required,StringLength(255)]
        public string AgencyInstagram { get; set; }

        public string AgencyTwitter { get; set; }

        public string AgencyFacebook { get; set; }

        public string AgencyLinkedin { get; set; }

        public string AgencyYoutube { get; set; }

        public bool AgencyIsComplated { get; set; }

        [ForeignKey("CompanyID")]
        public Company Company { get; set; }
        [ForeignKey("LogID")]
        public Log Log { get; set; }
        public virtual ICollection<AgencyCompany> AgencyCompanies { get; set; }
        
        public virtual ICollection<User> Users { get; set; }

        public virtual ICollection<Log> Logs { get; set; }
    }

    public class AgencyConfiguration : IEntityTypeConfiguration<Agency>
    {
        public void Configure(EntityTypeBuilder<Agency> builder)
        {
            builder.HasKey(agency => agency.ID);

            builder.HasMany(a => a.Logs)
                .WithOne(a => a.Agency)
                .HasForeignKey(a=>a.ID)
                .OnDelete(DeleteBehavior.Restrict);

            builder.HasMany(us => us.Users)
                .WithOne(us => us.Agency)
                .HasForeignKey(au=>au.ID)
                .OnDelete(DeleteBehavior.Restrict);

            builder.HasMany(ac => ac.AgencyCompanies)
                .WithOne(ac => ac.Agency)
                .OnDelete(DeleteBehavior.Restrict);
        }
    }

我有一个这样的 UnitOfWork:

public class UnitOfWork : IUnitOfWork
    {
        private TradeTurkDBContext _context;
        public UnitOfWork(TradeTurkDBContext context)
        {
            _context = context;
            RepositoryAgency = new RepositoryAgency(_context);
        }
        public IRepository Repository { get; private set; }
        public IRepositoryAgency RepositoryAgency { get; private set; }
        public int Complete()
        {
            return _context.SaveChanges();
        }
        public void Dispose()
        {
            _context.Dispose();
        }
    }

我在我的基础模型上继承了那个 ID。 当我没有在基本模型中定义 ID 但我已经在它上面设置了我的映射时,问题就得到了解决。

那么如何在代理模型中不使用 AgencyID 的情况下解决该错误?

解决方法

外键在详细信息(或子)表中。因此,例如一个用户,应该有一个 AgencyId 作为外键。

builder.Entity<User>()
    .HasOne(u => u.Agency)
    .WithMany(a => a.Users)
    .HasForeignKey(u => u.AgencyId)
    .OnDelete(DeleteBehavior.Restrict);

这个键自动指向主(或父)表的主键。

User.ID 是主键。 User.AgencyId 是一个外键,它(自动)与主键 Agency.ID 相关联。

例如见:Configure One-to-Many Relationships using Fluent API in Entity Framework Core

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...