这是定义一对多关系的适当方法吗

时间:2019-03-23 18:37:39

标签: c# asp.net-core .net-core entity-framework-core

我在这里有两个模型。财产和用户。 我需要在这里创建一对多关系。一个用户可以具有许多属性。每个媒体资源都有一个用户。

我必须像这样在模型中链接到相应的模型。

  

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方法中编写一个实体生成器。

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

您在此处创建的是一对一关系。为了使这种关系一对多,您将需要在用户模型上创建一个属性集合:

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,模型中的其他实体也将创建关系),或者您可以使用{{3}显式定义它}或Data Annotations。建议明确定义您的关系以及其他模型属性(例如,键,字符串字段长度)。这将有助于在代码中阐明这些属性,并确保Entity Framework以您期望的方式定义模型。

答案 1 :(得分:1)

由于您希望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; }
}