实体框架 - 外键 - 数据注释

时间:2012-01-11 16:17:39

标签: entity-framework

我在EF中使用数据注释,我有类:

[Table("Accounts")]
public class DbAccount
{
    public int Id { get; set; }
    public string Username { get; set; }

    public virtual DbLicense License { get; set; }
}

[Table("Licenses")]
public class DbLicense
{
    public int Id { get; set; }
    public int AccountId { get; set; }

    [ForeignKey("AccountId")]
    public virtual DbAccount Account { get; set; }
}

我必须如何装饰属性公共虚拟DbLicense许可证{get;组; }

EF throw

无法确定类型'DbLicense'和'DbAccount'之间关联的主要结束。必须使用关系流畅API或数据注释显式配置此关联的主要结尾。

这项工作做得很好:

modelBuilder.Entity<DbAccount>()
            .HasRequired(x => x.License)
            .WithRequiredPrincipal();

但我怎么能用注释写这个?

1 个答案:

答案 0 :(得分:7)

配置一对一关系时,Entity Framework要求依赖关系的主键也是外键。

请改为尝试:

[Table("Accounts")]
public class DbAccount
{
    [Key]
    public int Id { get; set; }
    public string Username { get; set; }

    [InverseProperty("Account")]
    public virtual DbLicense License { get; set; }
}

[Table("Licenses")]
public class DbLicense
{
    [Key, ForeignKey("Account")]
    public int Id { get; set; }
    public int AccountId { get; set; }
    [InverseProperty("License")]
    public virtual DbAccount Account { get; set; }
}
相关问题