我有以下实体类生成匹配代码,因此我可以确保不输入重复匹配。
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
的调用代码需要附加嵌套的Company
和CompaniesHouseRecord
才能添加新的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);
}
}