从广泛的谷歌搜索中,我似乎不是第一个遇到这个问题的人,但我一直无法找到能够圆满解决它的人 - 我正在与遗留数据库集成,而且我是仅尝试与单个表集成(目前),但我对该模型的第一个查询执行大约需要 12 秒左右。正如预期的那样,第二次调用几乎是即时的。
接下来是我的 Entity Framework Code First 设置的全部内容:
public class PortalDatabase : DbContext
{
public DbSet<User> Users { get; set; }
public PortalDatabase():base("portalDatabase")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
User.ConfigureEntity(modelBuilder.Entity<User>());
}
}
public class User
{
public int ID { get; set; }
public string FullName { get; set; }
/// <summary>
/// Internal representation of the IsDisabled flag. This should not be
/// written to; use <see cref="IsDisabled"/> instead.
/// </summary>
internal byte IsDisabledInternal { get; set; }
public bool IsDisabled
{
get { return Convert.ToBoolean(this.IsDisabledInternal); }
set { this.IsDisabledInternal = Convert.ToByte(value); }
}
public int LoginAttempts { get; set; }
public string EmailAddress { get; set; }
public string Password { get; set; }
internal static void ConfigureEntity(EntityTypeConfiguration<User> entity)
{
entity.ToTable("Users");
entity.Property(model => model.ID)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
.HasColumnName("UserID");
entity.Property(model => model.FullName)
.HasColumnName("UserName");
entity.Property(model => model.IsDisabledInternal)
.HasColumnName("AccountLocked");
entity.Ignore(model => model.IsDisabled);
entity.Property(model => model.LoginAttempts)
.HasColumnName("LoginAttempts");
entity.Property(model => model.EmailAddress)
.HasColumnName("EmailAddress");
entity.Property(model => model.Password)
.HasColumnName("Password");
}
}
此代码示例需要 8-12 秒才能执行:
PortalDatabase database = new PortalDatabase();
IEnumerable<User> users = from user in database.Users
where user.ID == 66
select user;
我知道这个问题与元数据生成有关,它只生成一次,according a comment from ScottGu “大大提高了性能”:
The "code first" library uses the same underlying EF as the traditional approach - so the performance characteristics should be about the same. The "code first" library also includes aome smarts so that the meta-data that is retrieved for mapping to/from the database is cached - so that it only needs to be calculated once (which improves performance a lot).
但我所描述的性能是平均水平吗?我无法想象花 12 秒来执行一个简单的查询对于 Entity Framework 团队来说是可以接受的。我是不是误会他了?元数据缓存是否在 IIS 应用程序池等的生命周期内持续存在?这在某种程度上可能是可以接受的,尽管仍然不太理想。
如果我没有先使用代码,那么我就可以 use EdmGen.exe to generate my views ,据我所知,这将使我的应用程序更快。首先使用代码开发我的模型时是否有等效项?
2012 年 2 月 14 日更新:感谢 Pawel's post ,我能够产生我的观点。不幸的是,这并没有改变创建新 PortalDatabase 实例的速度,它仍然需要相同的时间。我知道正在使用 View ,因为我在构造函数中放置了一个断点,但这不会影响任何东西。
最佳答案
要使用 CodeFirst 生成 View ,请使用 EF Power Tools。在此处查看更多详细信息:http://blogs.msdn.com/b/adonet/archive/2011/05/18/ef-power-tools-ctp1-released.aspx
关于sql-server-2005 - Entity Framework 代码优先非常慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9261095/