繁体   English   中英

连接两个对象的实体框架问题

[英]Entity framework issue with join two objects

我有以下对象:

public class City
    {
        public int CityId { get; set; }
        public string Name { get; set; }
        public virtual ICollection<CityTranslation> CityTranslations { get; set; }
    }
public class CityTranslation
    {
        public int CityId { get; set; }
        public string LanguageCode { get; set; }
        public string Translation { get; set; }

        public virtual City City { get; set; }
    }

城市表在名称字段中包含默认语言值,其他翻译在城市翻译表中。
我在从语言获得价值方面存在问题。
我正在尝试执行以下操作:

public virtual IEnumerable<City> GetAllByLanguage(string language)
        {
            if (language != "en")
            {
                var data = from c in context.Cities
                           join t in context.CityTranslations
                           on c.CityId equals t.CityId
                           && t.LanguageCode == language
                           select c;
            }
            else 
            {
                return dbSet.ToList();
            }
        }

但是我正在编译错误。

运算符“ &&”不能应用于类型为“ int”和“ bool”的操作数

加上一些转换错误。
我应该怎么做才能从翻译表中获得价值?

其他人发现了这个问题,但是您甚至不需要加入-EF会处理这个问题:

var data = from t in context.CityTranslations
           where t.LanguageCode == language
           select t.City;      

对于多个值的联接,您需要使用匿名类型创建复合键,因此联接语句必须类似于

on new {t.CityId, t.languageCode} equals new {c.CityId, language}

第二个谓词不应成为连接的一部分:

var data = from c in context.Cities
           join t in context.CityTranslations
               on c.CityId equals t.CityId
           where t.LanguageCode == language

暂无
暂无

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

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