2015-08-31 14 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;} 
} 
相關問題