我正在閱讀Julia Lerman和Rowan Miller編寫的「Programming Entity Framework:DbContext」一書。如何獲得「編程實體框架:DbContext」示例運行?
我已經從http://www.thedatafarm.com/learnentityframework/downloadfiles/dbcontext/StartingSolution.zip下載了「BAGA」解決方案。我覺得這裏是一個完整的工具,因爲我無法獲取任何代碼示例在我的計算機上運行。
通常,當我使用實體框架時,我的配置中有一個連接字符串,它告訴實體框架要連接的數據庫以及要使用的憑證。
但是,在此BAGA解決方案中,找不到解決方案中任何位置的連接字符串或對數據庫的引用。我猜測代碼應該全部運行在本地或某些地方,但是當我輸入並運行任何示例查詢或更新時,計算機會暫停大約20秒,然後從SaveChanges
方法引發以下異常: 「提供者沒有返回一個ProviderManifestToken字符串」。
我猜這個解決方案應該使用內部數據庫,或者我應該在某處鍵入一個連接字符串,但是我沒有看到它在本書的哪裏告訴我如何使這個解決方案工作。
它明確指出該解決方案使用EF Code First。
在BAGA控制檯應用程序代碼如下所示:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Text;
using DataAccess;
using Model;
namespace BreakAwayConsole
{
class Program
{
static void Main(string[] args)
{
Database.SetInitializer(new InitializeBagaDatabaseWithSeedData());
// Call the latest example method here
// NOTE: Some examples will change data in the database. Ensure that you only call the
// latest example method. The InitializeBagaDatabaseWithSeedData database initializer
// (registered above) will take care of resetting the database before each run.
AddMachuPicchu();
}
// Add example methods here
private static void AddMachuPicchu()
{
using (var context = new BreakAwayContext())
{
var machuPicchu = new Destination
{
Name = "Machu Picchu",
Country = "Peru"
};
context.Destinations.Add(machuPicchu);
context.SaveChanges();
}
}
}
}
由於@Wyktor Zychla問,這裏是代碼BreakAwayContext.cs:
using System.Data.Entity;
using Model;
namespace DataAccess
{
public class BreakAwayContext : DbContext
{
public DbSet<Destination> Destinations { get; set; }
public DbSet<Lodging> Lodgings { get; set; }
public DbSet<Trip> Trips { get; set; }
public DbSet<Person> People { get; set; }
public DbSet<Reservation> Reservations { get; set; }
public DbSet<Payment> Payments { get; set; }
public DbSet<Activity> Activities { get; set; }
}
}
正如你可以在這裏看到,有沒有指定構造函數。
我已經添加了'BreakAwayContext'的代碼。沒有聲明構造函數,所以我會在哪裏放置連接字符串? –
如果沒有構造函數,EF將在默認配置文件的connectionstrings部分中查找以下格式的連接字符串:name =「DataAccess.BreakAwayContext」connectionString =「yourconnectionstringgorshere」provider =「System.Data.SqlClient」。 –
謝謝。明天我回來時我會試試這個。 –