实体框架代码首先加入 [英] Entity Framework Code First Left Join

查看:147
本文介绍了实体框架代码首先加入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我创建了一个简单的数据库首先在EF代码,但似乎有一个问题。



我想做的是查询DBContext来检索一个自定义对象CheckedTag,所有可用的标签和一个检查的布尔字段。



代码首先抽象出多对多表,我似乎找不到正确的查询。 / p>

我尝试过

  var qry = from D in Db。标签
from a in Db.Articles
其中(a.Id == articleId)
选择新CheckedTag
{
Id = t.Id,
Name = t.Name,
PermanentUrl = t.PermanentUrl,
Checked = t.Id == null? false:true
};

现在已经净了几个小时。



如果articleId为0,它将检索所有标签,并且检查将被设置为false,如果articleId是现有文章,则将返回所有标签,并将检查的标签设置为



任何人都可以提出我需要使用的查询来实现此结果?

解决方案

如果我理解正确,你想获得一个特定的文章(具有id'articleId),所有标签的列表(而不仅仅是它们),并放置一个已检查如果它有真的,否则为假。如果是这样,我会建议的查询:

  var checkedTags = from D in Db.Tags 
select new CheckedTag
{
Id = t.id,
Name = t.name,
PermanentUrl = t.PermanentUrl,
Checked = t.Articles.Any(a => ; a.Id == articleId)
};

希望这有帮助:)



强>编辑:用任何替换包含。谢谢@Yakimych。


I've created a simple DB in EF code first but appear to have hit a problem.

What I would like to do is, query the DBContext to retrieve a custom object CheckedTag that would have all of the available tags and a boolean field of checked.

Code First abstracts the Many-To-Many table and I can't seem to find the correct query.

I've tried

            var qry = from t in Db.Tags
                  from a in Db.Articles
                  where(a.Id == articleId) 
                  select new CheckedTag 
                         { 
                             Id = t.Id, 
                             Name = t.Name, 
                             PermanentUrl = t.PermanentUrl, 
                             Checked = t.Id == null ? false : true 
                         };

and scoured the net for a few hours now.

If the articleId were to be 0, it would retrieve all of the tags and checked would be set to false, if the articleId was for an existing article all of the tags would be returned and the checked tags would be set to true.

Can anyone suggest the query I need to use to retrieve to achieve this result?

解决方案

if I understand correctly, you would like to get, for a particular article (having as id 'articleId), the list of all the tags (not just those it has), and put a "Checked" to true if it does have it, false otherwise. If so, here's the query I would suggest:

var checkedTags= from t in Db.Tags
                 select new CheckedTag
                        {
                            Id = t.id,
                            Name = t.name,
                            PermanentUrl = t.PermanentUrl,
                            Checked = t.Articles.Any(a => a.Id == articleId)
                        };

Hope this helps :)

Edit: replaced "Contains" with "Any". Thanks @Yakimych.

这篇关于实体框架代码首先加入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆