我有一個用戶模型和定義實體框架的關係
public class User
{
public string UserID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName {
get
{
return (FirstName + " " + LastName).Trim();
}
}
public string EmailID { get; set; }
public UserAccessLabel AccessLabel { get; set; }
public string Password { get; set; }
public string PasswordStore {
get
{
string hashPass;
using (Encryption enc = new Encryption())
{
enc.Key = EncryptionKey.DefaultKey;
hashPass = enc.Encrypt(Password);
}
return hashPass;
}
set
{
string hashPass;
using (Encryption enc = new Encryption())
{
enc.Key = EncryptionKey.DefaultKey;
hashPass = enc.Decrypt(value);
}
Password = hashPass;
}
}
public byte[] Image { get; set;}
}
和fluentAPI配置類是
public class UserConfig : EntityTypeConfiguration<User>
{
public UserConfig()
{
ToTable("tblUsers");
HasKey(k => k.UserID);
Property(p => p.FirstName).IsRequired();
Property(p => p.LastName).IsRequired();
Property(p => p.PasswordStore).IsRequired().HasColumnName("Password");
Property(p => p.Image).HasColumnType("image");
Ignore(i => i.FullName);
Ignore(i => i.Password);
}
}
,我有很多的同類產品,類別,客戶等和其他模型每種模式都有創建和更新屬性,它是用戶。
而我的問題是,我是否必須創建所有模型集合屬性用戶模型?
像
public ICollection<Product> Products { get; set; }
public class ProductConfig:EntityTypeConfiguration<Product>
{
public ProductConfig()
{
ToTable("tblProducts");
HasKey(k => k.Code);
Property(p => p.Title).IsRequired();
Property(p => p.Title).HasMaxLength(100);
HasRequired(c => c.Category).WithMany(p => p.Products).HasForeignKey(f => f.CategoryID).WillCascadeOnDelete(false);
HasRequired(u => u.Created).WithMany(p => p.Products).HasForeignKey(f => f.CreatedUser).WillCascadeOnDelete(false);
HasRequired(u => u.Updated).WithMany(p => p.Products).HasForeignKey(f => f.UpdatedUser).WillCascadeOnDelete(false);
}
}
在此先感謝
但我不能夠從外鍵列訪問數據,存在於數據庫中的數據時,我通過使用簡單的SQL查詢像Created_UserID檢查,但在模型,可以根據產品型號顯示在已創建的屬性無效 – Siraj
如果您的意思是FK id列不是空的,但對象字段爲空,這是因爲它們並未默認加載。你可以通過調用擴展方法'Include'這樣 'context.Products.Include(「創建」)加載它們' – Random
是啊,這是我一直在尋找的答案。好的,非常感謝 – Siraj