如何映射这两个实体之间的关系

时间:2015-02-12 03:22:32

标签: c# .net entity-framework

我有以下两个实体

     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 个答案:

答案 0 :(得分: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; }
}

答案 1 :(得分: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).