2015-02-12 105 views
1

之間的關係,我有以下兩個實體如何映射這兩個實體

 public class Document 
    { 
      public int Id { get; set; } 
      public string Name { get; set; } 

      public virtual ICollection<UploadedFile> UploadedFiles{ get; set; } 
    } 

    public class UploadedFile 
    { 
     public int Id { get; set; } 
     public string FileName{get;set;} 
     public string EntityName {get;set;} 
     public string EntityId{get;set;} 
     public bool IsActive{get;set;} 
    } 

現在,我的要求是我要加載基於以下條件「Document.UploadedFiles」。

UploadedFile.EntityId=Document.Id && UploadedFile.IsActive==true && UploadedFile.EntityName="Document" 

如何映射UploadedFiles導航屬性的關係?

回答

2

例如,你可以使用LINQ和幫助方法的匹配條件:

bool IsTargetFile(UploadedFile file, int documentId) 
{ 
    bool isTargetId = file.EntityId == documentId; 
    bool isTargetName = file.EntityName == "Document"; 
    bool isActive = file.IsActive; 
    return isTargetId && isTargetName && isActive; 
} 
void Main() 
{ 
    var document = new Document { Id = 1, Name = "MyDocument" }; 
    var targetFile1 = new UploadedFile { EntityId = 1, EntityName = "Document", IsActive = true }; 
    var nonTargetFile1 = new UploadedFile { EntityId = 2, EntityName = "Document", IsActive = true }; 
    var nonTargetFile2 = new UploadedFile { EntityId = 1, EntityName = "WrongDocument", IsActive = true }; 
    var nonTargetFile3 = new UploadedFile { EntityId = 1, EntityName = "Document", IsActive = false }; 
    document.UploadedFiles = new List<UploadedFile> 
    { 
     targetFile1, nonTargetFile1, nonTargetFile2, nonTargetFile3 
    }; 
    var targetFiles = document.UploadedFiles.Where(file => IsTargetFile(file, document.Id)); 
    foreach (var file in targetFiles) 
     Console.WriteLine("{0} {1} {2}", file.EntityId, file.EntityName, file.IsActive); 
} 

幫助類:

public class Document 
{ 
    public int Id { get; set; } 
    public string Name { get; set; }  
    public virtual ICollection<UploadedFile> UploadedFiles { get; set; } 
} 

public class UploadedFile 
{ 
    public int Id { get; set; } 
    public string FileName { get; set; } 
    public string EntityName { get; set; } 
    public int EntityId { get; set; } 
    public bool IsActive { get; set; } 
} 
+0

這意味着,document.UploadedFiles有所有的記錄,不僅僅是滿足我提到的條件。你的答案就像是加載UploadedFile中的所有記錄,然後再次過濾它們。這不是我要找的。 – 2015-02-12 06:28:51

0

因爲沒有關聯的B/W表。所以你可以通過以下方法來完成。

首先找到所有的UploadedFile,它是.EntityId = Document.Id,如下所示。

UploadedFile tempRes = db.UploadedFile.where(r=>r.EntityId==Document.Id).select(); 

然後在temRes上選擇精確的結果查詢。

UploadedFile Res=tempRes.where(your rest condition).