Dre*_*rew 6 c# generics constructor entity-framework
所以我有这个办公室实体类:
[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;
}
}
Run Code Online (Sandbox Code Playgroud)
我正在实现一个通用存储库,我刚刚添加了这个方法来检查存储库中是否已存在实体:
public bool Exists<TEntity>(Guid key) where TEntity : class, IBusinessEntity
{
return (_context.Set<TEntity>().Find(key) != null);
}
Run Code Online (Sandbox Code Playgroud)
然后我写了以下测试代码:
public void TestExists1()
{
InitializeDatabase();
EFOffice testOffice = InitializeOffice1();
Debug.Assert(EFRepo.Exists<EFOffice>(testOffice.Id));
}
Run Code Online (Sandbox Code Playgroud)
InitializeOffice1()的方法如下:
private EFOffice InitializeOffice1()
{
EFOffice newOffice = new EFOffice(SparkTest.TestGuid1, SparkTest.TestGuid2, "Generic Address", "HQ");
return newOffice;
}
Run Code Online (Sandbox Code Playgroud)
该测试应该通过,因为我已经插入了InitializeOffice1()之前返回的办公室.但是,我收到以下错误:
System.Reflection.TargetInvocationException:调用目标抛出了异常.---> System.InvalidOperationException:类'Models.Employees.EF.EFOffice'没有无参数构造函数.
那么我将其添加到顶部显示的EFOffice类中:
private EFOffice()
{
}
Run Code Online (Sandbox Code Playgroud)
由于某种原因,测试现在通过.谁能解释一下发生了什么?并且无参数构造函数会产生不良副作用吗?重要的是,我插入的每个办公室都有一个id,一个tenantId,一个地址和一个businessName,如顶部的构造函数中所列.
Mar*_*als 11
链接到EntityFramework的所有实体都必须具有默认构造函数.
当实体框架从数据库查询映射到您的实体时,使用默认构造函数来实例化实体的新实例,以使用从数据库中检索的数据填充它.
如果您没有默认构造函数,Entity Framework不知道如何创建它的实例并抛出异常
类'Models.Employees.EF.EFOffice'没有无参数构造函数.
归档时间: |
|
查看次数: |
4020 次 |
最近记录: |