我正在http://msdn.microsoft.com/zh-cn/data/jj193542.aspx上执行EF-代码优先示例。这个例子很好用。该示例在我的硬盘驱动器上创建一个LocalDB,其中包含数据库文件.mdf和.ldf。
如果删除这两个文件,则会出现“无法打开数据库”异常,如果替换这些文件,它将起作用。如果我更改DbContext的名称,它将起作用。
这是我的问题:为什么在我第一次运行示例时没有出现异常?似乎在某处会记住文件名/上下文名称。解决这个问题的正确方法是什么?
下面的类和DBContext,在db.Blogs.Add(blog);处抛出异常
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
class Program
{
static void Main(string[] args)
{
using (var db = new BloggingContext())
{
// Create and save a new Blog
Console.Write("Enter a name for a new Blog: ");
var name = Console.ReadLine();
var blog = new Blog { Name = name };
db.Blogs.Add(blog);
db.SaveChanges();
// Display all Blogs from the database
var query = from b in db.Blogs
orderby b.Name
select b;
Console.WriteLine("All blogs in the database:");
foreach (var item in query)
{
Console.WriteLine(item.Name);
}
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
public class Blog
{
public int BlogId { get; set; }
public string Name { get; set; }
public virtual List<Post> Posts { get; set; }
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
public virtual Blog Blog { get; set; }
}
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
}
我真正想做的是了解通过“代码优先”方法在何处/何处生成数据库。经过研究,结果非常简单。您需要做的就是在app.config或web.config文件中创建一个连接字符串,类似...
<connectionStrings>
<add name = YourDBContextName
providerName = "System.Data.SqlClient"
connectionString = "Data Source = (localdb)\v11.0; AttachDbFilename = Path to MDF file ...
AttachDbFile指定将在何处创建数据库。您还必须将连接命名为与数据库上下文相同的名称。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句