假设我有这个简单的实体:
public class Person
{
public int PersonID { get; set; }
public string Name { get; set; }
}
Entity Framework 可以根据约定推断PersonID
字段是主键。但是,如果我给模型构建器这个类:
public class PersonCfg : EntityTypeConfiguration<Person>
{
public PersonCfg()
{
ToTable("Person", "Person");
HasKey(p => p.PersonID);
}
}
这会提高启动性能吗?我的想法是它可能会让 EF 减少反射并更快地启动应用程序,但我不知道它在幕后如何工作以了解它是否有任何影响。
最佳答案
要对此进行测试,您可以使用 DbModelBuilder 类自行构建模型并跟踪“编译”步骤的速度。
这是我的示例代码(LinqPad 脚本):
void Main()
{
// Initialize the overall system, but don't count the result.
BuildC();
DateTime startDateA = DateTime.Now;
BuildA();
DateTime.Now.Subtract(startDateA).TotalMilliseconds.Dump("A");
DateTime startDateB = DateTime.Now;
BuildB();
DateTime.Now.Subtract(startDateB).TotalMilliseconds.Dump("B");
}
public class PersonA
{
public int PersonAId { get; set; }
public string Name { get; set; }
}
private void BuildA()
{
var builder = new DbModelBuilder();
builder.Entity<PersonA>();
var model = builder.Build(new DbProviderInfo("System.Data.SqlClient", "2008"));
model.Compile();
}
public class PersonB
{
public int PersonBId { get; set; }
public string Name { get; set; }
}
private void BuildB()
{
var builder = new DbModelBuilder();
builder.Conventions.Remove<IdKeyDiscoveryConvention>();
builder.Entity<PersonB>()
.HasKey(p => p.PersonBId);
var model = builder.Build(new DbProviderInfo("System.Data.SqlClient", "2008"));
model.Compile();
}
public class PersonC
{
public int PersonCId { get; set; }
public string Name { get; set; }
}
private void BuildC()
{
var builder = new DbModelBuilder();
builder.Entity<PersonC>()
.HasKey(p => p.PersonCId);
var model = builder.Build(new DbProviderInfo("System.Data.SqlClient", "2008"));
model.Compile();
}
我得到 2.0004 毫秒到 2.0009 毫秒的结果。奇怪的是,删除约定会使操作花费更长的时间。
关于c# - 指定主键等信息是否会影响 EntityFramework 性能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23869166/