繁体   English   中英

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

[英]Why does adding a parameterless constructor to my entity model class work here? What are the implications?

所以我有这个办公室实体类:

[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:调用目标抛出了异常。 ---> System.InvalidOperationException:类'Models.Employees.EF.EFOffice'没有无参数构造函数。

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

private EFOffice()
{

}

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

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

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

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

类'Models.Employees.EF.EFOffice'没有无参数构造函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM