0

例如,我制作了简单的模型。

public class Publisher
{
    public int Id { get; set; }

    public string Title { get; set; }

    public Address Location { get; set; }

    public virtual ICollection<Book> Books { get; set; }
}

public class Address
{
    public string Country { get; set; }
    public string City { get; set; }
    public string Street { get; set; }
    public string HouseNumber { get; set; }
}  


public class Book
{
    public int Id { get; set; }

    public string Title { get; set; }

    public string Author { get; set; }

    public int LanguageId { get; set; }

    public int? PublisherId { get; set; }
}

我需要让出版商提供相关书籍。我知道如何使用 linq to 实体来做到这一点。是否可以使用实体 sql 解决问题?

    public class CatalogContext : DbContext {...}

    public List<Publisher> GetByCity(string city)
    {
        var result = new List<Publisher>();
        string queryString;
            queryString = String.Format(@"SELECT VALUE row(a,b) 
                                        FROM CatalogContext.Publishers AS a 
                                        join CatalogContext.Books AS b on a.Id = b.PublisherId
                                        WHERE a.Location.City = '{0}'", city);
        var rows = ((IObjectContextAdapter)_context).ObjectContext.CreateQuery<DbDataRecord>(queryString).ToList();
        return ???
    }

查询返回所需的数据,但它是List<DbDataRecord>- 对列表<publisher, book>。如何将其翻译为具有填充导航属性“书籍”的出版商列表?是否可以编写直接返回的查询List<Publisher>

4

1 回答 1

0

您可以执行以下操作:

var result = ObjectContext.Publishers.Include("Books").Include("Locations")
.Where(c => c.Location.City = "SOME_CITY").Select(c => c);

包括 - 基本上加入表格。

然后,您可以通过执行以下操作深入到书籍:

var test = result[0].Books;

为什么使用直接 sql 命令而不是 Entity Framework 代码样式?

于 2013-09-18T14:34:21.937 回答