我在Visual Studio中创建了实体数据模型.现在我有文件与SQL查询和从模型生成的C#类.
题:
生成类没有注释或代码(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知道用户必须首先存在(主体),并且地址如下.
从评论更新