0

我找到了数千个 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)");
    }
}

谢谢 !

4

3 回答 3

1

您不需要使用外键LanguageID

    public int LanguageID { get; set; }
    [ForeignKey("LanguageID ")]
    public virtual Language Language { get; private set; }  
于 2013-01-30T16:22:42.647 回答
0

解决了。我的导航属性语言有私人二传手

[ForeignKey("LanguageID")]
public virtual Language Language { get; private set; } 
于 2013-01-31T20:36:04.940 回答
0

将虚拟导航字段添加到您的用户表中,如果它不存在的话。即你在 POCO 类用户中有 LanguageId 和 Language。另一种选择是语言类中的导航字段返回给用户,即公共虚拟列表用户

但是让我们坚持拥有虚拟导航属性和外键 ID 字段的用户。

 ... the rest of User.....
    public int LanguageId
// nav relationship
    public virtual Language Language { set; get; }

// Now the FK declaration as you described should work in fluent API...
// Has required NAVIGATION property, its 1 to many and the I have a field for this FK value called X

modelBuilder.Entity<User>().Map(m =>
        {
            m.MapInheritedProperties();
            m.ToTable("Users");
        }).HasKey(x => x.ID).HasRequired(x => x.Language).WithMany().HasForeignKey(x => x.LanguageID);
于 2013-01-31T04:04:25.910 回答