我在EF中使用Data annotation,我有类:
[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; }
}
Run Code Online (Sandbox Code Playgroud)
我必须如何装饰属性public virtual DbLicense License {get; 组; }?
EF投掷
无法确定类型'DbLicense'和'DbAccount'之间关联的主要结束.必须使用关系流畅API或数据注释显式配置此关联的主要结尾.
这项工作很好:
modelBuilder.Entity<DbAccount>()
.HasRequired(x => x.License)
.WithRequiredPrincipal();
Run Code Online (Sandbox Code Playgroud)
但是如何用注释来编写呢?
小智 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; }
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
13851 次 |
最近记录: |