我找到了数千个 codefirst 关系的例子,但我不能做我的样本!
很多这样的错误:
“BL.Objects.User”类型的属性“LanguageID”上的 ForeignKeyAttribute 无效。在依赖类型“BL.Objects.User”上找不到导航属性“语言”。Name 值应该是有效的导航属性名称。
和相同相同...
我真的很想加载与用户的语言关联。(en, ru, es)
public abstract class BaseUser : FinanceBase<int>, IUser
{
[ForeignKey("Language")]
public int LanguageID { get; set; }
[ForeignKey("LanguageID")]
public virtual Language Language { get; private set; }
}
public class User : BaseUser
{
public override void GenerateID()
{
...
}
}
public abstract class BaseLanguage : FinanceBase<int>, ILanguage
{
#region Implementation of ILanguage
public string Code { get; set; }
public string Fullname { get; set; }
public string ImagePath { get; set; }
#endregion
}
public class Language : BaseLanguage
{
public override void GenerateID()
{
}
}
public class FinanceDatabaseContext : DbContext
{
public FinanceDatabaseContext()
{
Database.SetInitializer(new FinanceContextInitializer());
}
public DbSet<User> Users { get; set; }
public DbSet<Language> Languages { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().Map(m =>
{
m.MapInheritedProperties();
m.ToTable("Users");
}).HasKey(x => x.ID).HasRequired(x => x.Language).WithMany().HasForeignKey(x => x.LanguageID);
modelBuilder.Entity<Language>().Map(m =>
{
m.MapInheritedProperties();
m.ToTable("Languages");
}).HasKey(x => x.ID);
base.OnModelCreating(modelBuilder);
}
}
public class FinanceContextInitializer : DropCreateDatabaseIfModelChanges<FinanceDatabaseContext>
{
protected override void Seed(FinanceDatabaseContext context)
{
context.Database.ExecuteSqlCommand("ALTER TABLE Users ADD CONSTRAINT uc_Language UNIQUE(LanguageID)");
}
}
谢谢 !