EF 4.1 の RC バージョンを使用して、簡単な ASP.NET MVC 3 アプリケーションを作成しようとしています。モデルは 2 つあります。
public class Race
{
public int RaceId { get; set; }
public string RaceName { get; set; }
public string RaceDescription { get; set; }
public DateTime? RaceDate { get; set; }
public decimal? Budget { get; set; }
public Guid? UserId { get; set; }
public int? AddressId { get; set; }
public virtual Address Address { get; set; }
}
そして
public class Address
{
public int AddressId { get; set; }
public string Street { get; set; }
public string StreetCont { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
public virtual Race Race { get; set; }
}
新しいレースを挿入しようとすると、次のエラーが発生します。
タイプ 'rcommander.Models.Race' と 'rcommander.Models.Address' 間の関連付けのプリンシパル エンドを特定できません。この関連付けのプリンシパル エンドは、リレーションシップ Fluent API またはデータ アノテーションを使用して明示的に構成する必要があります。
RaceId を Races テーブルの主キーとして、AddressId を Addresses テーブルへの FK として自動的に認識するべきではないでしょうか? 何か見落としているのでしょうか?
ありがとう!
ベストアンサー1
ここでの問題は、両方のオブジェクトに相互参照があるため、EntityFramework が先頭キーがどこにあるか認識できないということのようです。何を達成したいのかよくわからないので、次のような方法を提案します。
public class Race
{
public int RaceId { get; set; }
public string RaceName { get; set; }
public string RaceDescription { get; set; }
public DateTime? RaceDate { get; set; }
public decimal? Budget { get; set; }
public Guid? UserId { get; set; }
public int? AddressId { get; set; }
public virtual Address Address { get; set; }
}
public class Address
{
public int AddressId { get; set; }
public string Street { get; set; }
public string StreetCont { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
}
2 番目のエンティティの Race への参照をスキップします。