在此ASP.NET MVC应用程序中,所有数据库信息都设置为“代码优先”'在申请中。 有一个名为' Customer'的Model类。已经迁移到数据库,并填充了五个客户
现在我要添加一个'导航类'称为MembershipType。每位客户将拥有四种不同的会员类型之一
看起来像这样
namespace WebApplication3.Models
{
public class MembershipType
{
public byte Id { get; set; }
public string Name { get; set; }
public byte DurationInMonths { get; set; }
public short Fee { get; set; }
public byte Discount { get; set; }
}
}
然后我将MembershipType和MembershipTypeId字段添加到现有的Customer类中,并尝试添加迁移&更新的数据库。
namespace WebApplication3.Models
{
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime? Birthday { get; set; }
//These two fields were added as a 'Navigation Class'
public MembershipType MembershipType { get; set; }
public byte MembershipTypeId { get; set; }
}
}
我在程序包管理器中更新数据库时出现错误
ALTER TABLE语句与FOREIGN KEY约束冲突" FK_dbo.Customers_dbo.MembershipTypes_MembershipTypeId"。冲突发生在数据库" aspnet-WebApplication3-20160817102050",table" dbo.MembershipTypes",column' Id'。
我查看了我最近制作的其他节目,但没有这个外键'导航类未在数据库中填充之前的问题。
我试图理解为什么外键发生了这个错误...
答案 0 :(得分:0)
要使此EF约定起作用,您的MembershipType
类应该有一组Customers:
public class MembershipType
{
public byte Id { get; set; }
public string Name { get; set; }
public byte DurationInMonths { get; set; }
public short Fee { get; set; }
public byte Discount { get; set; }
public virtual ICollection<Customer> Customers {get; set;}//this needs to be present
//otherwise EF is not able to know what type of relationship to create
}