Burak
Burak

Reputation: 527

An item with the same key has already been added in Entity Framework Core SQL raw

I have two entities,

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

For select all the books I am trying :

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

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

But I got the exception shown here, which tells me that Name column already exists, but I got confused because they are different types.

An item with the same key has already been added. Key: Name```

Upvotes: 1

Views: 5876

Answers (2)

Chameera
Chameera

Reputation: 217

If you're using EF Core why fall back to using raw SQL? but i think u can use inside your controller

public YourContext Context { get; }

public YourController(YourContext context)
    {
        Context = context;

    }

var book=Context .Books.Include(b => b.Author);

Upvotes: 0

Joaqu&#237;n
Joaqu&#237;n

Reputation: 1136

Books and Authors both have a column called name. You should indicate in the query the table and field instead of 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()

Also this class should be like this since AuthorId is already in the Author Class

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

   public Author Author { get; set; }
}

Upvotes: 3

Related Questions