
题:
生成类没有注释或代码(Fluent API).是吗?我试图运行我的应用程序,但抛出异常:
无法确定类型“Runnection.Models.Address”和“Runnection.Models.User”之间关联的主体结束.必须使用关联流畅的API或数据注释来明确地配置此关联的主要结束.
我读到我不能使用Fluent API与“Model First”.那我该怎么办?
码:
用户
public partial class User{ public User() { this.Events = new HashSet<Event>(); this.CreatedEvents = new HashSet<Event>(); } public int ID { get; set; } public string Firstname { get; set; } public string Lastname { get; set; } public string Photo { get; set; } public int EventID { get; set; } public string Nickname { get; set; } public OwnerType OwnerType { get; set; } public NetworkPlaceType PlaceType { get; set; } public virtual ICollection<Event> Events { get; set; } public virtual Address Address { get; set; } public virtual ICollection<Event> CreatedEvents { get; set; } public virtual Owner Owner { get; set; }} 地址
public partial class Address{ public int ID { get; set; } public string Street { get; set; } public string StreetNumber { get; set; } public string City { get; set; } public string ZipCode { get; set; } public string Country { get; set; } public virtual User User { get; set; }} 上下文
// Model First不使用此方法
protected overrIDe voID OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Address>().Hasrequired(address => address.User) .WithrequiredDependent(); modelBuilder.Entity<User>().Hasrequired(user => user.Address) .WithrequiredPrincipal(); base.OnModelCreating(modelBuilder); }解决方法 您必须以一对一的关系指定主体. public partial class Address{ [Key,ForeignKey("User")] public int ID { get; set; } public string Street { get; set; } public string StreetNumber { get; set; } public string City { get; set; } public string ZipCode { get; set; } public string Country { get; set; } public virtual User User { get; set; }} 通过指定FK约束,EF知道用户必须首先存在(主体),并且地址如下.
Further reading at MSDN.
Also,see this SO answer.
从评论更新
在设计器中,选择关联(用户和地址之间的行).在属性窗口中,使用参考约束上的[…]按钮或(或双击该行).将校长设为用户.
总结以上是内存溢出为你收集整理的c# – 无法确定关联的主体结束 – 实体框架模型首先全部内容,希望文章能够帮你解决c# – 无法确定关联的主体结束 – 实体框架模型首先所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)