私はエンティティフレームワークを使用しています(コードが最初にあります)。コードファースト(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);
}
}
(http://stackoverflow.com/questions/5281974/code-first-independent [EFは必要ありません] -associations-vs-foreign-key-associations/5282275#5282275)を使用して、FKを専用プロパティに格納します。 –