【发布时间】:2017-09-14 20:17:11
【问题描述】:
我的 sqlserver 中有一个名为 Fruit 的数据库。我想创建一个 C# 控制台应用程序(.net 核心)来访问数据并将其保存为用户输入数据。 我有一个名为 Fruits 的类和一个名为 FruitDbContext 的 dbContext,它存储 dbSet 如何创建依赖注入,以便可以轻松地将模型轻松保存到不同的数据库?目前,我只想专注于 Microsoft SQL Server,而不是担心其他数据库。
我的水果课:
using System.Linq;
using System.Threading.Tasks;
namespace ConsoleApp1.Entity
{
public class Fruit
{
public string ID { get; set; }
public string FruitName { get; set; }
public string FruitColor { get; set; }
}
}
我的 FruitDbContext 类
namespace ConsoleApp1.Entity
{
public class FruitDbContext : DbContext
{
public DbSet<Fruit> Fruits { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionBuilder)
{
optionBuilder.UseSqlServer(@"Server = xxx; Database=Test; Integrated Security = True");
}
}
}
我的主程序:我的目的只是启动并使用一些种子记录填充我现有的数据库
using ConsoleApp1.Entity;
using System;
namespace ConsoleApp1
{
public class Program
{
public static void Main(string[] args)
{
using (var db = new FruitDbContext())
{
db.Fruits.AddRange(new Fruit { FruitName = "Orange", FruitColor = "Green" },
new Fruit { FruitName = "Banana", FruitColor = "Yellow" });
var count=db.SaveChanges();
Console.WriteLine($"{count} records added");
foreach (var f in db.Fruits)
{
Console.WriteLine($"Name -{f.FruitName}\t\t Color - {f.FruitColor}");
}
}
Console.ReadLine();
}
}
}
当我尝试保存更改时:我遇到了以下错误:
System.Data.SqlClient.SqlException: Invalid object name 'Fruits'.
我可能了解抱怨的内容,但我不知道如何正确解决它,因为我是 entityframeworkcore 的新手。如果您在实体框架上做了很多工作并能给我一些提示,我们将不胜感激。
这是我的 project.json
{
"buildOptions": {
"emitEntryPoint": true
},
"dependencies": {
"Microsoft.EntityFrameworkCore.Design": "1.1.1",
"Microsoft.EntityFrameworkCore.SqlServer": "1.1.1",
"Microsoft.EntityFrameworkCore.SqlServer.Design": "1.1.1",
"Microsoft.EntityFrameworkCore.Tools": "1.1.0",
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.0.1"
}
},
"frameworks": {
"netcoreapp1.0": {
"imports": "dnxcore50"
}
},
"tools": {
"Microsoft.EntityFrameworkCore.Tools": "1.1.0",
"Microsoft.EntityFrameworkCore.Tools.DotNet": "1.0.0-preview3-final"
},
"version": "1.0.0-*"
}
我的项目结构很简单:
我需要做什么来解决这个问题? 更新:
SQL 中的我的表
USE [Test]
GO
/****** Object: Table [dbo].[Fruit] Script Date: 4/16/2017 10:53:45 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Fruit](
[ID] [uniqueidentifier] NOT NULL,
[FruitName] [nvarchar](50) NULL,
[FruitColor] [nvarchar](50) NULL,
CONSTRAINT [PK_Fruit] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
【问题讨论】:
-
您有一个名为“Fruits”的数据库表吗?
-
不,我有一张叫 Fruit 的桌子
标签: c# visual-studio-2015 dependency-injection entity-framework-core