代码优先使用数据注释的多种关系的一种方式

时间:2015-08-31 16:40:41

标签: entity-framework ef-code-first

我的应用程序中有两个模型:StockReport。报告可以有很多股票,股票可以在许多报告中使用。

public enum ElectionType 
{
    MANAGER =1 , 
    INSPECTOR , 
    BOTH
}
public class Report
{
    public Report()
    {
        Stocks = new List<Stock>();
    }

    public int ReportID { get; set; }

    [Required]
    public DateTime ShamsiDate { get; set; }

    public int? StockID { get; set; }

    [Required]
    public  ElectionType  ElectionType { get; set; }

    [ForeignKey("StockID")]
    public virtual ICollection<Stock> Stocks { get; set;}
}
public class Stock
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int StockID { get; set; }
    public int FinancialCode { get; set; }
    public String NationalCode { get; set; }
    public String FirstName { get; set; }
    public String LastName { get; set; }
    public String FatherName { get; set; }
    public String Place { get; set; }

    public int StockCount { get; set; }

    public int StockPrice { get; set; }
    public int StockSize { get; set; }

    public int StartStock { get; set; }

    public int EndStock { get; set; }

}

我想创建单向关系,因此无法从Report访问Stock。我写了这段代码,但它不起作用。

1 个答案:

答案 0 :(得分:0)

要使用注释执行此操作,您需要一个联结表:

public class ReportStock
{
    [Key, Column(Order = 1)]
    public int ReportID { get; set; }
    [Key, Column(Order = 2)]
    public int StockID { get; set; }

    [ForeignKey("ReportID")]
    public virtual Report Report { get; set;}

    [ForeignKey("StockID")]
    public virtual Stock Stock { get; set;}
}

然后更改您的报告类:

public class Report
{
    public Report()
    {
        ReportStocks = new List<ReportStock>();
    }

    public int ReportID { get; set; }

    [Required]
    public DateTime ShamsiDate { get; set; }

    [Required]
    public  ElectionType  ElectionType { get; set; }

    public virtual ICollection<ReportStock> ReportStocks { get; set;}
}