简体   繁体   中英

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

I have two tables.

Author Table --- AuthID PK

Contract Table --- 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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