Lambda表达式在C#EF 5代码第一 [英] Lambda Expression for Many to Many realtionship in C# EF 5 Code First

查看:298
本文介绍了Lambda表达式在C#EF 5代码第一的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用EF 5 Code First和VS 2012.
我有文章和标签类。每篇文章将至少有一个标签相关联。
请参见下面的类。

  public class Article 
{
public int ArticleId {得到;组; }
public virtual ICollection< ArticleTag>标签{get;组; }
}
public class Tag
{
public int TagId {get;组; }
public string TagName {get;组; }
}

public class ArticleTag
{
public int ArticleId {get;组; }
public int TagId {get;组; }

//导航属性
public virtual Article Article {get;组; }
public virtual Tag Tag {get;组; }
}

下面是我试过的代码。 requestTags 包含TadgIds列表。 repBase 是数据库上下文。但下面的代码正在恢复所有文章。

  var idList = requestTags.tags.Select(t => t.id)。 ToList(); 
var result = repBase.GetAll< Article>()。Select(tg => tg.Tags.Where(tk => idList.Contains(tk.TagId)))。

请hlep我获取给定的TagIds列表的文章列表。



提前感谢。

解决方案




  • 选择

    code>到其中

  • tg.Tags.Contains tg.Tags.Any



示例:

  var idList = requestTags.tags.Select(t => t.id).ToList(); 

var result = repBase.GetAll< Article>()。其中​​(tg => tg.Tags.Any(tk => idList.Contains(tk.TagId)))ToList ;


I'm using EF 5 Code First and VS 2012. I have classes for Articles and Tags. Each Article will have atleast one Tag associated. Please see the classes below.

public class Article
{
    public int ArticleId { get; set; }
    public virtual ICollection<ArticleTag> Tags { get; set; }
}
public class Tag
{
    public int TagId { get; set; }
    public string TagName { get; set; }
}

public class ArticleTag
{
    public int ArticleId { get; set; }
    public int TagId { get; set; }

    // navigation property
    public virtual Article Article { get; set; }
    public virtual Tag Tag { get; set; }
}

Below is the code I tried. requestTags contains the list of TadgIds. repBase is db context. But below code is returing all Articles.

var idList = requestTags.tags.Select(t => t.id).ToList();
 var result= repBase.GetAll<Article>().Select(tg => tg.Tags.Where(tk => idList.Contains(tk.TagId))).ToList();

Please hlep me to get list of articles for a given list of TagIds.

Thanks in advance.

解决方案

I think you are looking for this.

Change:

  • Select to Where
  • tg.Tags.Contains to tg.Tags.Any

example:

var idList = requestTags.tags.Select(t => t.id).ToList();

var result= repBase.GetAll<Article>().Where(tg => tg.Tags.Any(tk => idList.Contains(tk.TagId))).ToList();

这篇关于Lambda表达式在C#EF 5代码第一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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