简体   繁体   English

比较两个表ASP.Net MVC的ID

[英]Comparing the ID's of two Tables ASP.Net MVC

I have two tables. 我有两张桌子。

Author Table --- AuthID PK 作者表--- AuthID PK

Contract Table --- AuthID FK 合同表--- AuthID FK

I would like to restrict the Contract View "Author Name" Box to Authors that do not already have Contracts. 我想将合同视图“作者姓名”框限制为尚未拥有合同的作者。

I think I could do it with alot more code but I feel like there is a way to do it with a simple query and I am just missing it. 我想我可以用更多的代码做到这一点,但我觉得有一种方法可以通过一个简单的查询来实现它,我只是错过了它。

Here is my Code: 这是我的代码:

 public ActionResult Create()
    {
        var contract = new Contract();

        var allAuthors = db.Authors.Select(a => a.AuthID);
        var unusedAuthors = new List<Author>();
        foreach (var auth in allAuthors) {
            unusedAuthors = db.Contracts
                .Where(a => a.AuthID.GetHashCode() != auth.GetHashCode())
                .Select(a => a.Author).ToList();
        }




        ViewBag.AuthID = new SelectList(unusedAuthors, "AuthID", "AuthFirstName");
        return View(contract);
    }

you can try this: 你可以试试这个:

 var unusedAuthors =
    (from a in db.Authors
    join c in db.Contracts on a.AuthID equals c.AuthID into lrs
    from lr in lrs.DefaultIfEmpty()
    where lr ==null
    select  a).ToList() ;

you can do this 你可以这样做

var allAuthors = db.Authors.Select(a => a.AuthID).ToList();


var unusedAuthors = db.Contracts
                .Where(x => !(allAuthors.Contains(x.AuthID)))
                .Select(a => a.Author)
                .ToList();

no need to use foreach 不需要使用foreach

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM