简体   繁体   English

连接两个表时的C#实体框架

[英]C# entity framework when join two table

I have some tables,using Entity Framework 我有一些表,使用实体框架

UserTable 用户表

  • UserID 用户身份

BookTable 书桌

  • BookID 书号
  • BookName 书名

OwnTable 自己的表

  • UserID 用户身份
  • BookID 书号

now I can use: 现在我可以使用:

uw.ownRepository.GetData().where(v=>v.userid=1).select(o=>o.Book)

to get all the book I own.But If I want to get all the books , and note that whether the user own it or not 获取我拥有的所有书。但是,如果我想获取所有书,请注意用户是否拥有它

I have some solution 我有一些解决方案

1. 1。

select all the book, then for each one select once 选择所有书籍,然后为每本书选择一次

stupid solution = =" 愚蠢的解决方案= =“

2. 2。

    var s = from book in uw.bookRepository.GetData()                    
    join own in uw.ownRepository.GetData() on book.Id equals like.Id into ps
    from o in ps.DefaultIfEmpty()
    select new {bookName =book.name,IsOwn =o==null};

just some pseudocode. 只是一些伪代码。

I tried it and works fine. 我尝试了并且工作正常。

But I'm wondering if there is another better solution 但我想知道是否还有另一个更好的解决方案

if I want to select a strong type like 如果我想选择一个强类型

    select new Book{bookName =book.name,bookType=book.bookType, IsOwn =o==null};

in this case , if I have many field in bookTable , i have to assign every field. 在这种情况下,如果bookTable中有很多字段,则必须分配每个字段。

Does anybody have some idea? 有人知道吗?

This is really simple. 这真的很简单。 You want all books so you want to start your lambda express on books entity. 您需要所有书籍,因此要在书籍实体上启动Lambda Express。 In the example here, I have selected an anonymous type. 在这里的示例中,我选择了一个匿名类型。 However, you can select your predefined type. 但是,您可以选择预定义的类型。

Books.GetData().Select(b=> new {name = b.BookName , DoIOwnThisBook = OwnTable.GetData().Where()})

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

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