我想在实体框架中使用脚手架机制来自动创建MusicDBContext数据库和表,但是在编程时出现了问题。
创建如下所示的步骤:
1.创建一个控制台应用程序。
2.使用NuGet安装实体框架:PM> install-package Entity Framework
3.将以下代码插入App.Config中的 configuration 会话中:
<connectionStrings>
<add name="MusicDBContext"
connectionString="Data Source=(LocalDb)\MSSQLLocalDB;
Initial Catalog=MusicDBContext;Integrated Security=SSPI;
AttachDBFilename=|DataDirectory|\MusicDBContext.mdf"
providerName="System.Data.SqlClient" />
</connectionStrings>
4。在控制台中编写以下代码:
using System;
using System.Linq;
using System.Data.Entity;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
try
{
MusicDbContext db = new MusicDbContext();
Music music = new Music { Title = "Far Away From Home",
ReleaseDate = DateTime.Now };
db.Musics.Add(music);
db.SaveChanges();
db.Musics.ToList().ForEach(x => Console.WriteLine($"{x.ID},
{x.Title},{x.ReleaseDate}"));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
if(ex.InnerException != null)
{
Console.WriteLine(ex.InnerException.Message);
}
}
Console.ReadKey();
}
}
public class Music
{
public int ID { get; set; }
public string Title { get; set; }
public DateTime ReleaseDate { set; get; }
}
public class MusicDbContext : DbContext
{
public MusicDbContext() : base("MusicDBContext") { }
public DbSet<Music> Musics { set; get; }
}
}
但是,在运行时发生以下错误:
A file activation error occurred.
The physical file name '\\MusicDBContext.mdf' may be incorrect.
Diagnose and correct additional errors, and retry the operation.
CREATE DATABASE failed. Some file names listed could not be created.
Check related errors.
当我删除 connectionStrings 会话中的所有内容时,它运行正常。
实体框架使用SqlLocalDB的默认连接。
ConnectionString如下所示:
Data Source=(localdb)\\mssqllocaldb;Initial Catalog=MusicDBContext;Integrated Security=True;MultipleActiveResultSets=True
为什么名为 MusicDBContext 的连接有问题?
关键字 DataDirectory 有问题吗?