如何使用DbContext自动创建的表(OnModelCreating(DbModelBuilder))

时间:2012-11-21 18:08:27

标签: c# asp.net-mvc entity-framework ef-code-first

我创建了两个表之间的多对多关系

表格 MoviesHashTags 是由DbContext自动创建的。

我希望能够使用Linq

向MoviesHashTags表发送查询

问题是我没有任何模型,而DbContext没有给我任何使用它的选项。例如:

_db.MoviesHashTags.Select(i =>i.Id).Where(i => i.HashTagId==3)

如果没有_db.Database.ExecuteSqlCommand("QUERY")

,有没有办法做到这一点

示例:

我想把所有拥有HashTagId = 3

的Id

TABLE MoviesHashTags:

enter image description here

-------------------------------------------------------------------------

TABLE电影:

[DataContract]
public class Movie 
{
    [DataMember]
    public long Id { get; set; }
    *
    *
    *
    [DataMember]
    public ICollection<HashTag> HashTagsCollection { get; set; }

public Movie()
{
    HashTagsCollection = new HashSet<HashTag>();
} 

TABLE HashTag:

[DataContract]
public class HashTag
{
    [DataMember]
    public long HashTagId { get; set; }
    *
    *
    *
    [DataMember]
    public ICollection<Movie> MoviesCollection { get; set; }

    public HashTag()
    {
        MoviesCollection = new HashSet<Movie>();
    }

的DbContext:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Movie>().
    HasMany(c => c.HashTagsCollection).
    WithMany(p => p.MoviesCollection).
    Map(
        m =>
       {
        m.MapLeftKey("Id");
        m.MapRightKey("HashTagId");
        m.ToTable("MoviesHashTags");
        });
 }

答案:感谢@DigitalD

db.Movies.Where(m => m.HashTagsCollection.Any(h => h.HashTagId == hashTag.HashTagId)).Select(m => m.Id);

1 个答案:

答案 0 :(得分:1)

Linq应该能够处理以下事项:

var HashTag = _db.HashTags.Find(3); //or whatever method you need to get a single hashtag
var Movies = _db.Movies.Where(m => m.HashTagsCollection.Contains(HashTag))
                 .Select(m => m.Id);