EF Update DB启用迁移导航属性错误
本文关键字:导航 属性 错误 迁移 启用 Update DB EF | 更新日期: 2023-09-27 18:16:51
我正在使用MVC 5的EF迁移-然而我得到我认为/认为是/是一个非常常见的错误,但我已经看到了常见的解决方案,我已经得到:
属性'companyId'不能配置为导航属性。该属性必须是有效的实体类型,并且该属性应该具有非抽象的getter和setter。对于集合属性,类型必须实现ICollection,其中T是有效的实体类型。
在enable-migrations和update-database之前,查看我的系统中的测试数据是否在我进行此更改之前被清除。在ASN模型中,我添加了testAsn的字符串属性,以查看是否将其作为列添加到数据库中。我不确定这个错误是否与ASN或Contacts表/模型有关,但它们都具有相同的实现。
我是否误解了导航属性的使用?任何帮助都将非常感激。
[Table("Company")]
public class Company
{
[Key]
public int companyId { get; set; }
[Required(ErrorMessage="Company name required.")]
[StringLength(100)]
public string name { get; set; }
[Required(ErrorMessage = "Telephone required.")]
public string telephone { get; set; }
[Required(ErrorMessage="Registration Number required.")]
[StringLength(30)]
public string regNumber { get; set; }
// navigation properties of the models that belong to the company
public virtual IList<Asn> asns { get; set; }
public virtual IList<Contact> contacts { get; set; }
}
[Table("Asn")]
public class Asn
{
[Key]
public int asnId { get; set; }
public int companyId { get; set; }
[ForeignKey("companyId")]
// property I'm adding to test whether migrations is working
public string testAsn { get; set; }
// *******************************
// as pointed out in the correct answer, the property below
// this comment should be above testAsn
// *******************************
public virtual Company company { get; set; }
[Required] // always has value
public bool userBehalf { get; set; }
[Required] // always has value
public bool confirmAssignment { get; set; }
[Required(ErrorMessage="Prefix required.")]
public string prefixAnnounced { get; set; }
[Required(ErrorMessage="Pending Ticket ID required.")]
public string pendingTicket { get; set; }
[DataType(DataType.MultilineText)]
public string comments { get; set; }
public bool asNumType { get; set; }
public string reason { get; set; }
}
[Table("Contact")]
public class Contact
{
[Key]
public int contactId { get; set; }
public int companyId { get; set; }
[ForeignKey("companyId")]
public virtual Company company { get; set; }
[StringLength(100, MinimumLength=3)]
[Required(ErrorMessage="Contact name required.")]
public string name { get; set; }
[Required(ErrorMessage="Telephone required.")]
[StringLength(30, MinimumLength=11)]
public string telephone { get; set; }
[Required]
[RegularExpression(@"^([a-zA-Z0-9_'-'.]+)@(('[[0-9]{1,3}" +
@"'.[0-9]{1,3}'.[0-9]{1,3}'.)|(([a-zA-Z0-9'-]+'" +
@".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(']?)$",
ErrorMessage = "Email is not valid.")]
public string email { get; set; }
[Required(ErrorMessage = "Contact type required.")]
public string type { get; set; }
}
您在Asn
类中放错了ForeignKey
属性。它不是放在company
属性上,而是放在testAsn
属性上。