列表基于两个表的变量

时间:2014-01-06 02:10:05

标签: c# linq asp.net-mvc-4 ef-code-first

我的程序是各种各样的任务程序。我想要做的是为用户/员工构建一个用户界面,以查看他们在登录的当天必须完成的任务。

我有一个表,PostOne和PostEig,1-M。

  • PostOne是主表,其中包含有关单个任务的信息。
  • PostEig是分配给Post One中任务的用户表。

模型[简化]

public class PostOne
{
    public string One { get; set; }
    [Key]
    public string Two { get; set; }
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:dd-MMM-yyyy}", ApplyFormatInEditMode = true)]
    public DateTime ThrD { get; set; }
}

public class PostEig
{
    public string EigOne { get; set; }
    public string EigTwo { get; set; } //foreign key
    [Key]
    public string EigID { get; set; }
    [Required]
    public string EigA { get; set; }  //user login 
}

我遇到控制器问题。我甚至不确定如何开始实现我的目标所需的代码,所以我将尝试写出来:

  1. 调用PostEigs列表,其中EigA == User.Identity.Name
  2. 并从此列表中调用一个PostOnes列表,其中两个== EigTwo
  3. 并从此列表中调用PostOnes列表,其中ThrD == DateTime.UtcNow.Date
  4. 我确实尝试过这样的事情:

    public ActionResult SkedList()
    {
        return View(db.PostEigs.Where(m =>
                m.EigA == User.Identity.Name ||
                m.EigTwo == db.PostOnes.Where(o => o.ThrD == DateTime.UtcNow.Date)
                ).ToList());
    }
    

    如果不清楚,请告诉我。我感谢任何建议或解决方案,即使是在不同的方向。

1 个答案:

答案 0 :(得分:0)

听起来这是Inner Join的候选人。我发现在SQL方面更容易思考,然后将其转换为LINQ。

SQL查询:

SELECT 
    po.* 
FROM 
    PostOnes po
INNER JOIN 
    PostEig pe
ON 
    pe.EigTwo = po.Two
WHERE 
    pe.EigA = AUTH_NAME AND po.ThrD = TODAY()

C#LINQ查询:

var DB_PostEig = new List<PostEig>()
{
    new PostEig(){EigTwo = "Foo1", EigA =  "Foo"},
    new PostEig(){EigTwo = "Foo2", EigA =  "Foo"},
    new PostEig(){EigTwo = "Bar1", EigA =  "Bar"},
    new PostEig(){EigTwo = "Bar2", EigA =  "Bar"}
};

var DB_PostOnes = new List<PostOne>()
{
    new PostOne(){Two = "Foo1", ThrD = new DateTime(1900,1,1)},
    new PostOne(){Two = "Foo2", ThrD = new DateTime(2000,1,1)},
    new PostOne(){Two = "Foo3", ThrD = new DateTime(1900,1,1)},
    new PostOne(){Two = "Bar1", ThrD = new DateTime(1900,1,1)},
    new PostOne(){Two = "Bar2", ThrD = new DateTime(1900,1,1)}
};

var authName = "Foo";
var currentDate = new DateTime(1900,1,1);

//Not sure if this is the most optimal LINQ Query, but it seems to work.
var queryReturn = DB_PostOnes.Join(DB_PostEig.Where(x => x.EigA == authName), x => x.Two, y => y.EigTwo, (x, y) => x)
    .Where(z => z.ThrD == currentDate)
    .ToList();

queryReturn.ForEach(x => Console.WriteLine(x.Two + " - " + x.ThrD)); //Foo1 - 1/1/1900

编辑:

没有连接的LINQ查询

var queryTwo = DB_PostOnes
    .Where(x => DB_PostEig.Any(y => y.EigTwo == x.Two && y.EigA == authName) && x.ThrD == currentDate)
    .ToList();