[英]Do I need to use a property ClassId to represent a relationship in the Code First (Entity Framework)?
我正在使用實體框架(代碼優先)。
我想知道我是否真的需要使用具有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類中不使用profileid屬性時,
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);
}
}
您在問兩個問題。
我需要使用FK屬性嗎?
不,您不會,但是無論是否使用EF行為都會改變。 有關它的更多信息,請參見單獨的答案和鏈接的博客文章。
為什么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();
簡短的回答:是的。 這就是EF工作的方式。 它需要將外鍵存儲在專用屬性中。 您是否曾經從數據庫生成類結構? 它總是添加該鍵屬性。 在某些情況下,您不需要加載Profile
屬性,但是稍后您可能想要檢索它。 這就是專用的ProfileId
屬性的用途,它將從那里讀取鍵值並加載對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.