2015-08-31 15 views
0

我在我的应用程序中有两个模型: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; } 

} 

我想创建一个单向关系,所以就没有办法从Stock访问Report。我写了这段代码,但它不起作用。

+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;} 
} 
相关问题