加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 08:43:42 所属栏目:百科 来源:网络整理
导读:所以我有这个办公室实体类: [Table("office_entity")]public class EFOffice : EFBusinessEntity{ [Column("address")] [StringLength(250)] public string Address { get; set; } [Column("business_name")] [StringLength(150)] public string BusinessNa
所以我有这个办公室实体类:
[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()之前返回的办公室.但是,我收到以下错误:

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类中:

private EFOffice()
{

}

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

解决方法

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

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读