简体   繁体   中英

Entity Framework throws error: Invalid object name

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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