最近几周我一直在学习实体框架,接触过 ADO.Net 和一些 LINQ 语法。在您真正开始开发这些东西之前,我基本上找到了很多设置和接线要做。我在 Code First 方法中特别难过,也曾在 Julie Larnam 的热情博客中度过了一段时间。任何关于实体框架的书籍、文章或博客的建议,以加快我的学习和更深入的理解,我们将不胜感激。
谢谢阿拉西
最近几周我一直在学习实体框架,接触过 ADO.Net 和一些 LINQ 语法。在您真正开始开发这些东西之前,我基本上找到了很多设置和接线要做。我在 Code First 方法中特别难过,也曾在 Julie Larnam 的热情博客中度过了一段时间。任何关于实体框架的书籍、文章或博客的建议,以加快我的学习和更深入的理解,我们将不胜感激。
谢谢阿拉西
public class Person
{
public Int32 Id { get; set; }
public String Name { get; set; }
public String Email { get; set; }
// one-to-many relationship to Pet (EF picks up on this automatically)
public ICollection<Pet> Pets { get; set; }
}
public class Pet
{
public Int32 Id { get; set; }
public String Name { get; set; }
public String Breed { get; set; }
// foreign key back to person (EF picks up on this automatically)
public Person Owner { get; set; }
}
public MyContext : DbContext
{
public DbSet<Person> Persons { get; set; }
public DbSet<Pet> Pets { get; set; }
}
提示:连接字符串的名称应与您的上下文匹配。
<connectionStrings>
<add name="MyContext"
providerName="System.Data.SqlClient"
connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=MyContext;IntegratedSecurity=True;" />
</connectionStrings>
// automatically find the connection string matching the context name,
// as well as performs a check to see if:
// 1. The database exists
// 2. The schema is up-to-date
MyContext context = new MyContext();
context.Persons.Add(new Person {
Name = "Brad Christie",
Email = "bchristie@contoso.com"
});
context.SaveChanges();
您还可以使用 更改数据的生成方式Initializers
。例如,如果您想使用信息预先填充数据库,您可以执行以下操作:
public class MyContextInitializer
// this could be `DropCreateDatabaseAlways<TContext> or any other
// preexsting initializer:
: DropCreateDatabaseIfModelChanges<MyContext>
// you can also create your own explicitly if you implement the
// following interface, but that's a bit much starting out.
//: IDatabaseInitializer<MyContext>
{
protected override void Seed(MyContext context)
{
new List<Person> {
new Person {
Name = "Brad Christie",
Email = "bchristie@contoso.com",
Pets = new HashSet<Pet> {
new Pet {
Name = "Spot",
Breed = "Dalmation"
}
}
}, new Person {
Name = "Alaxi04",
Email = "Alaxi04@contoso.com",
Pets = new HashSet<Pet> {
new Pet {
Name = "Petey",
Breed = "Parrot"
}
}
}
}.ForEach(p => context.Persons.Add(p));
base.Seed(context);
}
}
在实践中:
// call this somewhere early on in the application (but only once!)
Database.SetInitializer<MyContext>(new MyContextInitializer());
// This can also be configured through the `web.config`:
<entityFramework>
<contexts>
<context type="MyNamespace.MyContext, MyAssembly">
<databaseInitializer type="MyNamespace.MyContextInitializer, MyAssembly" />
</context>
</contexts>
</entityFramework>
/* ***** */
// then use the context as normal:
MyContext context = new MyContext();
var petOwners = context.Persons.AsEnumerable();