2012-10-15 68 views
0

我有模型我需要創建LINQ到實體SQL查詢

public class GrandPrix 
{ 
    public int Id { get; set; } 

    [Required] 
    [Display(Name = "Имя")] 
    [DataType(DataType.Text)] 
    public string Name { get; set; } 

    public int LocationId { get; set; } 

    public int? ChampionchipId { get; set; } 

    public virtual Location Location { get; set; } 
    public virtual Championchip Championchip { get; set; } 
} 
    public class Location 
{ 
    public int Id { get; set; } 

    [Required] 
    [Display(Name = "Location")] 
    [DataType(DataType.Text)] 
    public string Name { get; set; } 

// public virtual ICollection<GrandPrix> GrandPrix { get; set; } 
} 

我需要

ViewBag.LocationId = new SelectList(db.Locations, "Id", "Name"); 

db.Locations 修改。凡(L => l.id不包含在db.Grandprix.Where(G => g.ChampionchipId == 1))

此查詢它的工作

SELECT Locations.Id as Id, Locations.Name as Name FROM dbo.Locations WHERE Locations.Id Not In (SELECT GrandPrixes.LocationId FROM GrandPrixes WHERE ChampionchipId = 1) 

對不起,我的英語和感謝您的幫助。

回答

1
db.Locations.Where(loc=>loc.GrandPrixes.Any(gp=>gp.ChampionshipId != 1)) 

如果您的FK關係設置正確,應該爲您提供位置信息。

否則

var gps = db.GrandPrixes.Where(gp=>gp.ChampionshipId == 1) 
         .Select(gp=>gp.Location.LocationId).ToList(); 
db.Locations.Where(loc=>!gps.Any(gp=>gp == loc.LocationId)) 
+0

'公共的ActionResult創建(INT championchipId = 0){風險GPX = db.GrandPrix。凡(GP => gp.ChampionchipId == championchipId)。選擇(GP => gp.Location .ID).ToList(); ViewBag.LocationId = new SelectList(db.Locations.Where(loc => gpx.All(gp => gp!= loc.Id)),「Id」,「Name」); ViewBag.ChampionchipId =新的SelectList(db.Championchips,「Id」,「Year」,championchipId);返回View(); }工作正常。謝謝。 –