私は次のクラスを持っています:
家主
[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; }
}
住宅物件
[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 を持つことができるため、関連付けは 1 対多です。メソッドを使用してデータベースにテスト データを追加しようとしています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 < ResidentialProperty > に暗黙的に変換できません」というエラーが発生します。
Seed() メソッドで 1 対多の関係をどのように実装しますか?
編集:
このタイプの関係を実装するために、コンテキスト クラスに次のコードを追加しました。ResidentialProperty は Landlord を 1 つだけ持つことができます。
modelBuilder.Entity<Landlord>()
.HasMany(x => x.ResidentialProperties)
.WithRequired()
.HasForeignKey(x => x.ResidentialPropertyId);
modelBuilder.Entity<ResidentialProperty>()
.HasRequired(x => x.UserProfile);
私はまだこのエラーが発生しています:
\tSystem.Data.Entity.Edm.EdmAssociationEnd: : 関係 'Landlord_ResidentialProperties' のロール 'Landlord_ResidentialProperties_Target' で多重度が無効です。従属ロールはキー プロパティを参照するため、従属ロールの多重度の上限は「1」でなければなりません。
私が間違っていることについてはまだ途方に暮れています。