实体框架 - 外键 - 数据注释 [英] Entity framework - Foreign key - data annotation

查看:97
本文介绍了实体框架 - 外键 - 数据注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

public virtual DbLicense License {get;组; }
}

[表(许可证)]
public class DbLicense
{
public int Id {get;组; }
public int AccountId {get;组; }

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

我必须装饰属性 public virtual DbLicense License {get ;组; }



EF throw



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



这个工作很好:

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

但是如何使用注释来写这个?

解决方案

当配置一对一关系时,实体框架要求从属关键的主键也是外键。



尝试这样做:

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

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

[表(许可证)]
public class DbLicense
{
[Key,ForeignKey(Account)]
public int Id {get;组; }
public int AccountId {get;组; }
[InverseProperty(License)]
public virtual DbAccount Account {get;组; }
}


I use Data annotation with EF and I have the classes:

[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; }
}

How I must decorate the property public virtual DbLicense License { get; set; } ?

EF throw

Unable to determine the principal end of an association between the types 'DbLicense' and 'DbAccount'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.

This work well:

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

But how i can write this with annotation using?

解决方案

When configuring one-to-one relationships, Entity Framework requires that the primary key of the dependent also be the foreign key.

Try this instead:

[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; }
}

这篇关于实体框架 - 外键 - 数据注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆