所以我有一个办公实体类:
[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:调用的目标引发了异常。-> System.InvalidOperationException:类'Models.Employees.EF.EFOffice‘没有无参数构造函数。
然后,我将其添加到顶部显示的EFOffice类中:
private EFOffice()
{
}出于某种原因,测试现在通过了。有人能解释一下这是怎么回事吗?没有参数的构造函数会产生不良的副作用吗?重要的是,我插入的每个办公室都有一个id、一个tenantId、一个地址和一个businessName,如顶部的构造函数所示。
发布于 2015-06-16 17:23:42
链接到EntityFramework的所有实体都必须具有默认构造函数。
当实体框架从数据库查询映射到实体时,使用默认构造函数实例化实体的新实例,以填充从数据库检索到的数据。
如果您没有默认的构造函数实体框架不知道如何创建它的实例并抛出异常
类“Models.Employees.EF.EFOffice”没有无参数构造函数。
https://stackoverflow.com/questions/30874113
复制相似问题