Entity Framework throws error: Invalid object name

0

I'm getting the following error with this sample I received, it looks correct by the manuals and docs I found.

There are a lot of books I found here and all looks have the same pattern of code that looks like this one I received from a friend last week.

I don't have much more detail about it but this form keep telling me its looks like mostly code then I need keep typing.

System.Data.SqlClient.SqlException
HResult=0x80131904
Message=Invalid object name 'Persons'.
Source=Core .Net SqlClient Data Provider

My code:

using System;
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;

namespace ConsoleApp
{
    public class BaseModel : DbContext
    {
        [Key]
        public int Id { get; set; }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            var strCnn = @"Data Source=localhost;Initial Catalog=TutorialDB;Integrated Security=True;Pooling=False";
            optionsBuilder.UseSqlServer(strCnn);
        }
    }
}

----------------

using System;
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;

namespace ConsoleApp.Model
{
    public class Person : BaseModel
    {
        public DbSet<Person> Persons { get; set; }

        public Person() {}

        public Person(int _id, string _name) {
            this.Id = _id;
            this.Name = _name;
        }

        public string Name { get; set; }
    }
}

----------------

using System;
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            using (Model.Person p = new Model.Person()) 
            {
                p.Persons.Add(new Model.Person(01, "Name001"));
                _ = p.SaveChanges();
            }
        }
    }   
}
c#
sql-server
entity-framework
asked on Stack Overflow Jun 28, 2019 by mark • edited Jun 28, 2019 by marc_s

1 Answer

0

As a wild stab in the dark, I'd say you havent actually added the configuration for the entities anywhere. You either need annotations of use the fluent configuration to tell EF where to look for things. Like this: https://www.entityframeworktutorial.net/efcore/configuration-in-entity-framework-core.aspx

answered on Stack Overflow Jun 28, 2019 by Robert Perry

User contributions licensed under CC BY-SA 3.0