所以我有这个办公室实体类:
[Table("office_entity")]
public class EFOffice : EFBusinessEntity
{
[Column("address")]
[StringLength(250)]
public string Address { get; set; }
[Column("business_name")]
[StringLength(150)]
public string BusinessName { get; set; }
public virtual ICollection<EFEmployee> Employees { get; set; }
public EFOffice(Guid id, Guid tenantId, string address, string businessName)
{
this.Id = id;
this.TenantId = tenantId;
this.Address = address;
this.BusinessName = businessName;
}
}
我正在实现一个通用存储库,我刚刚添加了这个方法来检查存储库中是否已存在实体:
public bool Exists<TEntity>(Guid key) where TEntity : class, IBusinessEntity
{
return (_context.Set<TEntity>().Find(key) != null);
}
然后我写了以下测试代码:
public void TestExists1()
{
InitializeDatabase();
EFOffice testOffice = InitializeOffice1();
Debug.Assert(EFRepo.Exists<EFOffice>(testOffice.Id));
}
InitializeOffice1()的方法如下:
private EFOffice InitializeOffice1()
{
EFOffice newOffice = new EFOffice(SparkTest.TestGuid1, SparkTest.TestGuid2, "Generic Address", "HQ");
return newOffice;
}
测试应该通过,因为我已经插入了InitializeOffice1()之前返回的office。但是,我收到以下错误:
System.Reflection.TargetInvocationException:调用目标抛出了异常。 ---&GT; System.InvalidOperationException:类'Models.Employees.EF.EFOffice'没有无参数构造函数。
然后我将其添加到顶部显示的EFOffice类中:
private EFOffice()
{
}
由于某种原因,测试现在通过了。谁能解释一下发生了什么?并且无参数构造函数会产生不良副作用吗?重要的是,我插入的每个办公室都有一个id,一个tenantId,一个地址和一个businessName,如顶部的构造函数中所列。
答案 0 :(得分:11)
链接到EntityFramework的所有实体都必须具有默认构造函数。
当Entity Framework从数据库查询映射到您的实体时,使用默认构造函数来实例化您的实体的新实例,以使用从数据库中检索的数据填充它。
如果您没有默认构造函数,Entity Framework不知道如何创建它的实例并抛出异常
类'Models.Employees.EF.EFOffice'没有无参数构造函数。