briddums
briddums

Reputation: 1846

EF Core: How to have models with different names from the tables

I have a database-first application with tables that have different names from my models. My application worked fine using fluent API until I added a model that had a one-to-many relationship with another model. It then started giving me the error:

SqliteException: SQLite Error 1: 'no such column: a0.AuthorAuthorId

Sample classes would be:

class Book
{
    public int BookId { get; set; }
    public string Title { get; set; }

    public Author Author {get; set; }
}

class Author
{
    public int AuthorId { get; set; }
    public string Name { get; set; }

    public ICollection<Book> Books { get; set; }
}

and my OnModelCreating is -

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Book>()
        .ToTable("tbl_Book")
        .HasKey(b => b.BookId);

    modelBuilder.Entity<Author>()
        .ToTable("tbl_Author")
        .HasKey(a => a.AuthorId);
}

I tried using .HasOne() and .WithMany() to specify the relationship between the tables. That did not work.

Upvotes: 0

Views: 1155

Answers (1)

atiyar
atiyar

Reputation: 8315

You haven't defined and configured a foreign key property, so EF is looking for one with its own naming convention. To avoid the issue add a foreign key property in Book model -

class Book
{
    public int BookId { get; set; }
    public string Title { get; set; }
    public int AuthorId { get; set; }

    public Author Author {get; set; }
}

and configure it manually by adding the following code to OnModelCreating method -

modelBuilder.Entity<Book>()
        .HasOne(p=> p.Author)
        .WithMany(p=> p.Books)
        .HasForeignKey(p=> p.AuthorId);

Upvotes: 2

Related Questions