我正在使用EF Migrations和MVC 5 - 但是我得到了我的想法/想法/是一个非常常见的错误,但我见过的常见解决方案,我已经得到了:
无法将属性“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; }
}
答案 0 :(得分:1)
您错放了ForeignKey
课程中的Asn
属性。它不是放在company
属性上,而是放在testAsn
属性上。