说我有这个简单的实体:
public class Person
{
public int PersonID { get; set; }
public string Name { get; set; }
}
实体框架可以按惯例推断PersonID
字段是主键。但是,如果我给模型构建器这个类:
public class PersonCfg : EntityTypeConfiguration<Person>
{
public PersonCfg()
{
ToTable("Person", "Person");
HasKey(p => p.PersonID);
}
}
这会改善启动性能吗?我的想法是它可能允许EF更少地反映并更快地启动应用程序,但我不知道它是如何在幕后工作以了解它是否有任何影响。
答案 0 :(得分:1)
要对此进行测试,您可以使用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.0004ms到2.0009ms的结果。奇怪的是,删除约定使得操作需要更长的时间。