I am working with two classes Company and Visitor that have a one-to-many relationship.
public class Company
{
public int CompanyID { get; set; }
public string CompanyName { get; set; }
public virtual ICollection<Visitor> Visitors { get; set; }
}
public class Visitor
{
public int VisitorID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public int CompanyID { get; set; }
public bool SendNewsletter { get; set; }
public virtual Company Company { get; set; }
}
I have a page where a Visitor can fill out information about themselves. The idea is that if a Company is not in the db, it will get added to the list. If the CompanyName the Visitor enters matches a name in the db, the Company is associated with the Visitor, rounding out its required info, which is then added to its own db.
var companyExists = db.Companies.Any(c => c.CompanyName == visitor.Company.CompanyName);
if(companyExists)
{
var existingCompany = db.Companies.SingleOrDefault(c => c.CompanyName == visitor.Company.CompanyName);
visitor.CompanyID = existingCompany.CompanyID;
visitor.Company = existingCompany;
}
db.Visitors.Add(visitor);
db.SaveChanges();
This code works but it seems redundant. I am associating the Visitor's CompanyID with the existing Company and then doing the same for the Company. Everything I read suggests that updating the Visitor's CompanyID should be sufficient but if I don't map the existingCompany to the Visitor's Company parameter, a second CompanyID is created. I feel like I'm missing some crucial point and am hoping someone here can point me in the right direction.