Skip to main content
 首页 » 编程设计

c#之Entity Framework之在 Seed() 方法中实现一对多外键关系

2024年02月20日12qlqwjy

我有以下类(class):

楼主

[Table("Landlord")] 
public class Landlord : UserProfile 
{ 
    public static int LandlordProfileViews { get; set; } 
 
    // A Landlord can have many ResidentialProperties 
    [ForeignKey("ResidentialPropertyId")] 
    public virtual ICollection<ResidentialProperty> ResidentialProperties { get; set; } 
 
} 

住宅属性(property)

[Table("ResidentialProperty")] 
public class ResidentialProperty 
{ 
    [Key] 
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] 
    public int ResidentialPropertyId { get; set; } 
    // ... 
 
    // A ResidentialProperty has 1 Landlord 
    [ForeignKey("UserId")] 
    public int UserId { get; set; } 
    public virtual UserProfile UserProfile { get; set; } 
} 

Landlord 可以有很多 ResidentialProperties,所以关联是一对多的。我正在尝试使用 Seed() 方法将测试数据添加到我的数据库中。我的问题是我不知道如何在方法中定义关系的多端。以下是我尝试过的:

var residentialProperties = new List<ResidentialProperty> 
{ 
    // Property 1 associated with LandLord 1 
    new ResidentialProperty { /* properties */ }, 
    // ... 
 } 
 
var landlords = new List<Landlord> 
 { 
    new Landlord { /* properties */ ResidentialProperties = residentialProperties.FirstOrDefault(x => x.ResidentialPropertyId == 1) }, 
    // ... 
 } 

ResidentialProperties = residentialProperties.FirstOrDefault(x => x.ResidentialPropertyId == 1) 给出“无法将类型 ResidentialProperty 隐式转换为 ICollection 错误。

如何在 Seed() 方法中实现一对多关系?

编辑:

我在我的上下文类中添加了以下内容来尝试实现这种类型的关系:一个房东可以有很多 ResidentialProperties。 ResidentialProperty 只能有一个房东:

modelBuilder.Entity<Landlord>() 
            .HasMany(x => x.ResidentialProperties) 
            .WithRequired() 
            .HasForeignKey(x => x.ResidentialPropertyId); 
 
modelBuilder.Entity<ResidentialProperty>() 
            .HasRequired(x => x.UserProfile); 

我仍然收到此错误:

\tSystem.Data.Entity.Edm.EdmAssociationEnd: : Multiplicity is not valid in Role 'Landlord_ResidentialProperties_Target' in relationship 'Landlord_ResidentialProperties'. Because the Dependent Role refers to the key properties, the upper bound of the multiplicity of the Dependent Role must be '1'..

仍然不知道我做错了什么。

请您参考如下方法:

您需要返回 ResidentalProperties 列表。您的查询 ResidentialProperties = residentialProperties.FirstOrDefault(x => x.ResidentialPropertyId == 1) 仅返回一个 ResidentialProperty 实体。只需执行 ResidentialProperties = residentialProperties

编辑:您可以通过单个配置进行多对一设置。您还必须指定外键。

            //ResidentialProperty has 1 Landlord , 
            //Landlord has many ResidentialProperties 
            modelBuilder.Entity<ResidentialProperty>().HasRequired(a=> a.UserProfile) 
                .WithMany(c=> c.ResidentialProperties) 
                .HasForeignKey(a=> a.UserId);