我用这个教程使用VS2015安装EF:
EF - Console Application to New Database
基本上是:
- 确保您的目标的.NET Framework 4.5.1或更高版本。
- 确保您使用的是最新版本的nuget package manager
- 安装这两个包:
- EntityFramework.MicrosoftSqlServer - 预
- EntityFramework.Commands - 预
我我们创建了一个简单的DbContext,其中包含两个实体:
using Microsoft.Data.Entity;
using System.Collections.Generic;
public class SampleContext : DbContext
{
public DbSet<Person> People { get; set; }
public DbSet<Tenant> Tenants { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
// Visual Studio 2015 | Use the LocalDb 12 instance created by Visual Studio
optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;");
// Visual Studio 2013 | Use the LocalDb 11 instance created by Visual Studio
// optionsBuilder.UseSqlServer(@"Server=(localdb)\v11.0;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Configure the name of the foreign key
modelBuilder.Entity<Person>()
.HasOne(p => p.Tenant)
.WithMany(t => t.Persons)
.HasConstraintName("MyForeignKey");
// Configure the name of a unique index
modelBuilder.Entity<Person>().HasAlternateKey(p => p.Email).ForSqlServerHasName("MyUniqueEmail");
}
}
public class Person
{
public int PersonId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual Tenant Tenant { get; set; }
}
public class Tenant
{
public Tenant()
{
Persons = new HashSet<Person>();
}
public int TenantId { get; set; }
public string Name { get; set; }
public virtual ICollection<Person> Persons { get; set; }
}
所以配置外键的名称:
modelBuilder.Entity<Person>()
.HasOne(p => p.Tenant)
.WithMany(t => t.Persons)
.HasConstraintName("MyForeignKey");
要配置一个唯一索引的名称:
modelBuilder.Entity<Person>().HasAlternateKey(p => p.Email).ForSqlServerHasName("MyUniqueEmail");
这时就需要使用包来创建迁移您的上下文Manager控制台:
最后更新使用软件包管理器控制台数据库:
使用SQL Server Management Studio中,我可以检查我的索引的名字:
您使用的是什么版本的EntityFramework? – Rob
实体框架7但大部分东西在6似乎工作.. – chris
它不重复EF核心有完全不同的API。 –