简体   繁体   English

如何在实体框架中注释外键

[英]how annotate foreign key in entity framework

historically, I need the following data model: 从历史上看,我需要以下数据模型:

public class Banner
{
    [Key]
    public int Id { get; set; }

    ???
    public int IdForResult { get; set; }
    ???
    public BannerResult Result { get; set; }
}

public class BannerResult
{
    [Key]
    public int Id { get; set; }

    ???
    public int IdForBanner { get; set; }
    ???
    public Banner Banner { get; set; }
}

how should i annotate it in entity framework? 我应该如何在实体框架中对其进行注释?

When configuring foreign keys eg, one-to-one relationships, Entity Framework requires that the primary key of the dependent also be the foreign key. 在配置外键(例如一对一关系)时,实体框架要求从属的主键也应为外键。

Sample code 样例代码

[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; }
}
public class Banner
{
    [Key]
    public int Id { get; set; }
    public int IdForResult { get; set; }
    [ForeignKey("IdForResult")]
    public BannerResult Result { get; set; }
}

public class BannerResult
{
    [Key]
    public int Id { get; set; }
    public int IdForBanner { get; set; }
    [ForeignKey("IdForBanner")]
    public Banner Banner { get; set; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM