static void Main(string[] args) { var builder = new ModelBuilder(); builder.Configurations.Add(new BookConfiguration()); builder.Entity<Person>(); builder.Entity<Publisher>().Property(p => p.Name).IsRequired().HasMaxLength(50);
var model = builder.CreateModel();
Console.Write("Enter an ISBN for the new book: "); var isbn = Console.ReadLine();
Console.Write("Enter a title for the new book: "); var title = Console.ReadLine();
// Data access with DbContext using (var context = new SimpleBookCatalog("CodeFirstWalkthrough", model)) { var book = new Book { ISBN = isbn, Title = title, FirstPublished = DateTime.Today, IsFiction = false, Author = new Author { FirstName = "Rowan", LastName = "Miller" }, Publisher = new Publisher { Name = "EF Books" } };
我自己手动添加了一个App.config的配置文件,在这里面配置的要生成的数据库信息,我刚才试了一下,这个配置文件确实没起作用,不过我又把配置信息写到代码里,依然不好用,出现异常:“在与 SQL Server 建立连接时出现与网络相关的或特定于实例的错误。未找到或无法访问服务器。请验证实例名称是否正确并且 SQL Server 已配置为允许远程连接。 (provider: SQL Network Interfaces, error: 26 - 定位指定的服务器/实例时出错)”,这又是什么问题呢?
using (var context = new SimpleBookCatalog(@"Data Source=192.168.253.31\sqlexpress;Initial Catalog=CodeFirstWalkthroughTest;uid=sa;pwd=uf_1234;Integrated Security=True;Pooling=False;User Instance=True", model)) { var book = new Book { ISBN = isbn, Title = title, FirstPublished = DateTime.Today, IsFiction = false, Author = new Author { FirstName = "Rowan", LastName = "Miller" }, Publisher = new Publisher { Name = "EF Books" } };
context.Books.Add(book); context.SaveChanges(); }
[其他解释]
我把sqlexpress去掉了,问题又回去了,异常:“用户 '' 登录失败。该用户与可信 SQL Server 连接无关联。”,还是用windows身份验证的方式登录的,不知道这里到底应该怎么控制??? [其他解释] 你服务器名称到底是192.168.253.31?还是192.168.253.31\sqlexpress?这两个不同的,后面这个一般是本地机上用的实例,服务器上安装一般不装sqlexpress版本的 [其他解释]