c# – 为什么在我的实体模型类中添加无参数构造函数在这里工作?有什么影响?

前端之家收集整理的这篇文章主要介绍了c# – 为什么在我的实体模型类中添加无参数构造函数在这里工作?有什么影响?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
所以我有这个办公室实体类:
  1. [Table("office_entity")]
  2. public class EFOffice : EFBusinessEntity
  3. {
  4.  
  5. [Column("address")]
  6. [StringLength(250)]
  7. public string Address { get; set; }
  8.  
  9. [Column("business_name")]
  10. [StringLength(150)]
  11. public string BusinessName { get; set; }
  12.  
  13. public virtual ICollection<EFEmployee> Employees { get; set; }
  14.  
  15. public EFOffice(Guid id,Guid tenantId,string address,string businessName)
  16. {
  17. this.Id = id;
  18. this.TenantId = tenantId;
  19. this.Address = address;
  20. this.BusinessName = businessName;
  21. }
  22. }

我正在实现一个通用存储库,我刚刚添加了这个方法来检查存储库中是否已存在实体:

  1. public bool Exists<TEntity>(Guid key) where TEntity : class,IBusinessEntity
  2. {
  3. return (_context.Set<TEntity>().Find(key) != null);
  4. }

然后我写了以下测试代码

  1. public void TestExists1()
  2. {
  3. InitializeDatabase();
  4. EFOffice testOffice = InitializeOffice1();
  5. Debug.Assert(EFRepo.Exists<EFOffice>(testOffice.Id));
  6. }

InitializeOffice1()的方法如下:

  1. private EFOffice InitializeOffice1()
  2. {
  3. EFOffice newOffice = new EFOffice(SparkTest.TestGuid1,SparkTest.TestGuid2,"Generic Address","HQ");
  4. return newOffice;
  5. }

该测试应该通过,因为我已经插入了InitializeOffice1()之前返回的办公室.但是,我收到以下错误

System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. —> System.InvalidOperationException: The class ‘Models.Employees.EF.EFOffice’ has no parameterless constructor.

那么我将其添加到顶部显示的EFOffice类中:

  1. private EFOffice()
  2. {
  3.  
  4. }

由于某种原因,测试现在通过.谁能解释一下发生了什么?并且无参数构造函数会产生不良副作用吗?重要的是,我插入的每个办公室都有一个id,一个tenantId,一个地址和一个businessName,如顶部的构造函数中所列.

解决方法

链接到EntityFramework的所有实体都必须具有默认构造函数.

当实体框架从数据库查询映射到您的实体时,使用默认构造函数来实例化实体的新实例,以使用从数据库中检索的数据填充它.

如果您没有默认构造函数,Entity Framework不知道如何创建它的实例并抛出异常

The class ‘Models.Employees.EF.EFOffice’ has no parameterless constructor.

猜你在找的C#相关文章