代码之家  ›  专栏  ›  技术社区  ›  Major Productions

实体框架4-数据透视表和导航属性

  •  1
  • Major Productions  · 技术社区  · 14 年前

    视频游戏可以在多个平台上使用(例如,侠盗猎车手系列可以在Xbox360、PlayStation3、PC、PSP甚至任天堂DS上使用)。当然,每个平台都有一个游戏库。因此,我有一个名为GamesPlatforms的表,它充当游戏和平台之间的轴心:

    • GamesPlatformsID—int,主键,标识
    • GameID—int,来自Games表的外键
    • PlatofrmID—int,来自Platforms表的外键

    我只是很难理解如何将其转换为EF4导航属性,以及如何编写LINQ查询而不是传统的连接。是不是像这样简单:

    using(var context = MyEntities();)
    {
        var gamePlatformCount = (from gpc in context.Games
                                where gpc.GamesPlatforms.Platforms.Name == "XBox 360"
                                select gpc).Count();
    }
    

    ??

    2 回复  |  直到 14 年前
        1
  •  1
  •   Craig Stuntz    14 年前

    几乎。你想要的是:

    using(var context = new MyEntities()
    {
        var gamePlatformCount = (from gpc in context.Games
                                where gpc.GamesPlatforms.Any(p => p.Platforms.Name == "XBox 360")
                                select gpc).Count();
    }
    
        2
  •  2
  •   jeroenh    14 年前

    如果将游戏和平台之间的链接显式建模为一个实体,则可以这样定义查询:

            var q = from g in context.GameSet
                    from gp in g.GamePlatforms
                    where gp.Platform.Name == "Xbox 360"
            var count = q.Count()
    

    但是,不需要将多对多链接表作为对象模型的显式部分。您可以直接在(对象)模型中建模多对多关系,并由数据库中的链接表支持。

    所以在你的实体模型中,你只需要游戏和平台,它们之间有一个多对多的关系。然后,查询将类似于:

            var q = from g in context.GameSet
                    from p in g.Platforms
                    where p.Name == "Xbox 360"
    
            var count = q.Count();