2016-10-09 2 views
0

Ich habe die folgende Entitätsklasse, die einen Übereinstimmungscode generiert, damit ich sicherstellen kann, dass doppelte Übereinstimmungen nicht eingegeben werden.Soll ich DbContext an einen Konstruktor übergeben?

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); 
     } 
    } 
} 

Ich dachte, es wäre einfacher, der Konstruktor haben die Erstellung des Codes zu behandeln, so habe ich den Konstruktor auch die Beziehung füllen.

Das Problem dabei ist, dass der anrufende Code, der die MatchMethod erstellt dann die verschachtelten Company befestigen muss und CompaniesHouseRecord, bevor sie die neuen MatchMethod hinzufügen kann.

Das fühlt sich alles plump an und ich frage mich, ob der Konstruktor vielleicht die DbContext als Parameter nehmen sollte oder ich sollte das anders machen?

ich es so machte und es funktioniert gut, aber ich bin nicht sicher, ob dies eine schlechte Art und Weise ist, es zu tun:

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); 
    } 
} 

Antwort

0

Warum nicht verwenden (wheter Sie mit Entity Framework oder edmx gehen) einige navigation properties?

Sie werden automatisch die Beziehungen für Sie abrufen.

+0

Wie würde ich Navigationseigenschaft verwenden, um dies zu erreichen? – Guerrilla

Verwandte Themen