我应该将DbContext传递给enttity构造函数吗?

时间:2016-10-09 20:16:22

标签: c# entity-framework

我有以下实体类生成匹配代码,因此我可以确保不输入重复匹配。

public class CompanyMatch
{
    public int ID { get; set; }
    /// <summary>
    /// {CompanyID}-{CompanyMatchMethod}-{CompaniesHouseRecordID}
    /// </summary>
    [StringLength(100)]
    [Index(IsUnique = true)]
    [Required]
    public string MatchCode { get; set; }
    public CompanyMatchMethod CompanyMatchMethod { get; set; }
    public virtual Company Company { get; set; }
    public virtual CompaniesHouseRecord CompaniesHouseRecord { get; set; }

    public CompanyMatch(int companyId, CompanyMatchMethod matchMethod, int companiesHouseId)
    {
        this.MatchCode = companyId.ToString() + "-" + matchMethod + "-" + companiesHouseId.ToString();
        this.CompanyMatchMethod = matchMethod;
        using (var db = new PlaceDBContext())
        {
            this.Company = db.Companies.Find(companyId);
            this.CompaniesHouseRecord = db.CompaniesHouseRecords.Find(companiesHouseId);
        }
    }
}

我认为让构造函数处理代码的创建会更容易,所以我让构造函数也填充了关系。

问题在于,创建MatchMethod的调用代码需要附加嵌套的CompanyCompaniesHouseRecord才能添加新的MatchMethod。< / p>

这一切都让人觉得笨拙,我想知道构造函数是否应该将DbContext作为参数,或者我应该采用不同的方式?

我是这样做的,它运作正常,但我不确定这是不是一个坏方法:

public class CompanyMatch
{
    public int ID { get; set; }
    /// <summary>
    /// {CompanyID}-{CompanyMatchMethod}-{CompaniesHouseRecordID}
    /// </summary>
    [StringLength(100)]
    [Index(IsUnique = true)]
    [Required]
    public string MatchCode { get; set; }
    public CompanyMatchMethod CompanyMatchMethod { get; set; }
    public virtual Company Company { get; set; }
    public virtual CompaniesHouseRecord CompaniesHouseRecord { get; set; }

    public CompanyMatch(int companyId, CompanyMatchMethod matchMethod, int companiesHouseId, DbContext db)
    {
        this.MatchCode = companyId.ToString() + "-" + matchMethod + "-" + companiesHouseId.ToString();
        this.CompanyMatchMethod = matchMethod;
        this.Company = db.Companies.Find(companyId);
        this.CompaniesHouseRecord = db.CompaniesHouseRecords.Find(companiesHouseId);
    }
}

1 个答案:

答案 0 :(得分:0)

为什么不使用(当你使用实体框架或edmx时)某些navigation properties

他们会自动为你取得关系。