1

我正在使用實體框架(代碼優先)。我是否需要使用屬性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); 
    } 
} 

回答

1

你在問兩個問題。

我需要使用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

[EF不需要(http://stackoverflow.com/questions/5281974/code-first-independent -associations-vs-foreign-key-associations/5282275#5282275)將FK存儲在專用屬性中。 – 2011-12-26 12:41:16