我正在使用實體框架(代碼優先)。我是否需要使用屬性ClassId來代表Code First(實體框架)中的關係?
我想知道如果我真的需要使用Id的屬性與另一個實體的關係,如下面的代碼。
public class User
{
public int Id { get; set; }
public string Login { get; set; }
public string Password { get; set; }
public int ProfileId { get; set; }
public Profile Profile{ get; set; }
}
public class Profile
{
public int Id { get; set; }
public string Description{ get; set; }
}
對於這種方式,當我插入一個用戶通過設置profileid屬性執行完美。
但是,當我沒有在Profile類使用簡檔屬性,
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; }
}
執行插入方法增加了一個配置文件記錄。爲什麼?
我的映射:
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);
}
}
[EF不需要(http://stackoverflow.com/questions/5281974/code-first-independent -associations-vs-foreign-key-associations/5282275#5282275)將FK存儲在專用屬性中。 – 2011-12-26 12:41:16