1

私はエンティティフレームワークを使用しています(コードが最初にあります)。コードファースト(Entity Framework)の関係を表すためにClassIdプロパティを使用する必要がありますか?

以下のコードのように、別のエンティティとの関係にIdを持つプロパティを使用する必要が本当に必要かどうかを知りたいと思います。

このように、profileidプロパティを設定してユーザーを挿入すると、完全に実行されます。

しかし、私はプロファイルクラスでのプロファイルIDプロパティを使用しないとき、

public class User 
{ 
    public int Id { get; set; } 
    public string Login { get; set; } 
    public string Password { get; set; } 
    public Profile Profile{ get; set; } 
} 

public class Profile 
{ 
    public int Id { get; set; } 
    public string Description{ get; set; } 
} 

実行insertメソッドは、別のプロファイルのレコードを追加します。どうして?

マイマップ:

public class EntityMapping<Entity> : EntityTypeConfiguration<Entity> where Entity : EntityBase 
{ 
    public EntityMapping() 
    { 
     HasKey(e => e.Id); 
     Property(e => e.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); 
    } 
} 

public class UserMapping : EntityMapping<User> 
{ 
    public UserMapping() : base() 
    { 
     ToTable("USER"); 
     Property(p => p.Id).HasColumnName("USER_CD_USER"); 
     Property(p => p.Login).HasColumnName("USER_TX_LOGIN").HasMaxLength(10).IsRequired(); 
     Property(p => p.Password).HasColumnName("USUA_TX_PASSWORD").HasMaxLength(8).IsRequired(); 
     HasRequired(e => e.Profile).WithMany(p => p.Users).Map(p => p.MapKey("PROF_CD_PROFILE")); 
    } 
} 

public class ProfilelMapping : EntityMapping<Profile> 
{ 
    public ProfileMapping() 
     : base() 
    { 
     ToTable("PROFILE"); 
     Property(p => p.Id).HasColumnName("PROF_CD_PROFILE"); 
     Property(p => p.Description).HasColumnName("PROFILE_DS_PROFILE").HasMaxLength(20).IsRequired(); 
     HasMany(e => e.Users).WithRequired(p => p.Profile); 
    } 
} 

答えて

1

2つの質問があります。

FKプロパティを使用する必要がありますか?

EFの動作の変更は、使用しない場合は変わりません。詳しくはseparate answerとリンクされているブログ記事です。

なぜEFがプロファイルを再度挿入するのですか?

既存のエンティティとの関係を作成するには特別な注意が必要です。 EFはあなたのエンティティがデータベースに存在するかどうかをチェックしません。あなたはそれをEFに伝えなければなりません。ここでは(データベースからプロファイルをロードせずに)それを達成するためにどのように多くの方法の一つです:

var user = GetNewUserSomewhere(); 
context.Users.Add(user); 

// Dummy profile representing existing one. 
var profile = new Profile() { Id = 1 }; 
// Informing context about existing profile. 
context.Profiles.Attach(profile); 

// Creating relation between new user and existing profile 
user.Profile = profile; 

context.SaveChanges(); 
-1

短い答え:はい。それはEFの仕組みです。専用のプロパティに外部キーを格納する必要があります。データベースからクラス構造を生成したことはありますか?そのキープロパティは常に追加されます。場合によってはProfileプロパティを読み込む必要はありませんが、後で取得することができます。これは、専用のProfileIdプロパティが使用されている場合、そこからキー値を読み取り、オブジェクトをロードします。

+0

(http://stackoverflow.com/questions/5281974/code-first-independent [EFは必要ありません] -associations-vs-foreign-key-associations/5282275#5282275)を使用して、FKを専​​用プロパティに格納します。 –

関連する問題