简体   繁体   English

C#。 EF实体sql。 如何获得具有相关对象的实体?

[英]c#. EF entity sql. How to get entity with related objects?

I have made simple model for example. 例如,我已经制作了简单的模型。

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; }
}

I need to get publishers with related books. 我需要让出版商提供相关书籍。 I know how to do it using linq to entities. 我知道如何使用linq到实体。 Is it possible to solve a problem using entity sql? 使用实体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 ???
    }

Query returns required data but it's List<DbDataRecord> - list of pairs <publisher, book> . 查询返回所需的数据,但它是List<DbDataRecord> -对<publisher, book>对的列表。 How to translate it to list of publishers with filled navigation property "Books"? 如何将其转换为导航属性为“ Books”的出版商列表? Is it possible to write query which directly returns List<Publisher> ? 是否可以编写直接返回List<Publisher>查询?

you can do the following: 您可以执行以下操作:

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

Include - basically joins the table. 包含-基本加入表。

Then you can drill down to books by doing the following: 然后,您可以通过执行以下操作来深入研究书籍:

var test = result[0].Books;

Why are you using direct sql command instead of Entity Framework code style? 为什么要使用直接sql命令而不是Entity Framework代码样式?

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

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