簡體   English   中英

C#。 EF實體sql。 如何獲得具有相關對象的實體?

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

例如,我已經制作了簡單的模型。

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到實體。 使用實體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>對的列表。 如何將其轉換為導航屬性為“ Books”的出版商列表? 是否可以編寫直接返回List<Publisher>查詢?

您可以執行以下操作:

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代碼樣式?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM