我这里有两个型号。财产和用户。我需要在这里建立一对多的关系。一个用户可以拥有许多属性。每个属性都有一个用户。
我必须在模型中链接相应的模型,如此。
Property.cs
public class Property
{
public int Id { get; set; }
public string Town { get; set; }
public string County { get; set; }
public User User { get; set; }
public int UserId {get; set}
}
User.cs
public class User : IdentityUser<int>
{
public ICollection<UserRole> UserRoles { get; set; }
public Property Property { get; set; }
}
是否可以完成这项工作,还是需要在数据上下文文件中的onmodelcreate方法中编写实体构建器。
谢谢你的帮助。
你在这里创造的是一对一的关系。要使其成为一对多关系,您需要在User模型上创建一组Properties:
public class Property
{
public int Id { get; set; }
public string Town { get; set; }
public string County { get; set; }
public User User { get; set; }
public int UserId {get; set; }
}
public class User : IdentityUser<int>
{
public ICollection<UserRole> UserRoles { get; set; } = new List<UserRole>();
// This must be a collection
public ICollection<Property> Properties { get; set; } = new List<Property>();
}
实体框架将自动创建给定上述代码的关系(并且将对模型中的其他实体执行此操作,只要您遵守特定的conventions),或者您可以使用Data Annotations或Fluent API明确定义它。建议明确定义您的关系以及其他模型属性(例如,键,字符串字段长度)。这将有助于澄清代码中的这些属性,并确保实体框架以您想要的方式定义模型。
由于您希望User
具有许多属性,因此需要将Property
属性设置为集合。否则这将是一对一的关系。
public class User : IdentityUser<int>
{
public ICollection<UserRole> UserRoles { get; set; }
public ICollection<Property> Properties { get; set; }
}
由于您想立即使用属性集合,因此需要在构造函数中初始化它。
public class User : IdentityUser<int>
{
public User() {
Properties = new List<Property>();
}
public ICollection<UserRole> UserRoles { get; set; }
public ICollection<Property> Properties { get; set; }
}