C# 设置导航属性不需要';不设置外键
我正在尝试使用以下代码为数据库添加种子:C# 设置导航属性不需要';不设置外键,c#,entity-framework,C#,Entity Framework,我正在尝试使用以下代码为数据库添加种子: private static Contact ContactCreate(DbContext ctx, Company Company, string Description) { var contact = ctx.Contacts.Create(); contact.Description = Description; contact.Company = Company; // #1 ctx.Co
private static Contact ContactCreate(DbContext ctx, Company Company, string Description) {
var contact = ctx.Contacts.Create();
contact.Description = Description;
contact.Company = Company; // #1
ctx.Contacts.AddOrUpdate(c => c.Description, contact);
ctx.SaveChanges();
return ctx.Contacts.First(c=>c.Description == Description);
}
保存更改时失败,因为未设置contact.CompanyId,并且不满足外键约束。如果在下一行之前更改行#1,代码将正确执行:
contact.CompanyId = Company.Id; // #2
这是通常的行为吗
当属性“Company”具有导航时,是否需要外键“CompanyId”
我认为这是重复的,因为EntityFramework知道“公司”中的关键属性是什么,应该为您管理它
编辑:这是从模型优先方法生成的代码
public partial class Contact : IAuditable
{
public int Id { get; set; }
public string Description { get; set; }
public int CompanyId { get; set; }
public virtual Company Company { get; set; }
}
public partial class Company : IAuditable
{
public Company()
{
this.Contacts = new HashSet<Contact>();
}
public int Id { get; set; }
public string Description { get; set; }
public virtual ICollection<Contact> Contacts { get; set; }
public virtual Contact Contact { get; set; }
}
公共部分类联系人:IAuditable
{
公共int Id{get;set;}
公共字符串说明{get;set;}
public int CompanyId{get;set;}
公共虚拟公司公司{get;set;}
}
公共部分类公司:IAuditable
{
上市公司()
{
this.Contacts=newhashset();
}
公共int Id{get;set;}
公共字符串说明{get;set;}
公共虚拟ICollection联系人{get;set;}
公共虚拟联系人联系人{get;set;}
}
您能说明如何定义联系人
类吗?完成。。。我还增加了公司级