【问题标题】:An item with the same key has already been added in Entity Framework Core SQL raw已在 Entity Framework Core SQL raw 中添加了具有相同键的项
【发布时间】:2020-11-17 13:48:32
【问题描述】:

我有两个实体,

Book.cs

public class Book 
{
   public int Id { get; set }
   public string Name { get; set; }
   public string ReferenceNo { get; set; } 

   public int AuthorId { get; set; }
   public Author Author { get; set; }
}

Author.cs

public class Author 
{
   public int Id { get; set }
   public string Name { get; set; }
   
   public List<Book> Books { get; set; }
}

选择我正在尝试的所有书籍:

var query = "select * from Books as book join Authors as author on author.Id = book.AuthorId";

_context.Books.FromSqlRaw(query).ToList()

但是我得到了这里显示的异常,它告诉我Name 列已经存在,但我很困惑,因为它们是不同的类型。

已添加具有相同密钥的项目。键:名称```

【问题讨论】:

    标签: c# sql-server entity-framework .net-core entity-framework-core


    【解决方案1】:

    Books 和 Authors 都有一个名为 name 的列。您应该在查询中指明表和字段,而不是 select *

    var query = "select book.Id, book.Name, book.ReferenceNo, author.Id, author.Name from Books as book join Authors as author on author.Id = book.AuthorId";
    
    _context.Books.FromSqlRaw(query).ToList()
    

    这个类也应该是这样的,因为 AuthorId 已经在 Author 类中了

    public class Book 
    {
       public int Id { get; set }
       public string Name { get; set; }
       public string ReferenceNo { get; set; } 
    
       public Author Author { get; set; }
    }
    

    【讨论】:

    • 如果您需要两个Name 列,您必须提供至少一个列别名
    • 感谢您的回答,但对于您的第二个回答,如果您不包括作者,那么您应该如何从 Book 实体中获取 AuthorId? :)
    【解决方案2】:

    如果您使用的是 EF Core,为什么要回退到使用原始 SQL? 但我认为你可以使用 在你的控制器内部

    public YourContext Context { get; }
    
    public YourController(YourContext context)
        {
            Context = context;
    
        }
    
    var book=Context .Books.Include(b => b.Author);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-20
      • 2021-05-14
      • 2017-08-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多