我試圖將我的存儲庫更新到EF5,但遇到了一些錯誤。我看了一下週圍的stackoverflow類似的錯誤發現了幾個問題/答案,但不幸的是,同樣的答案沒有解決我的問題。實體類型不是模型的一部分,EF 5
這是我的錯誤:
The entity type User is not part of the model for the current context.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
這是我的DbContext類:
public abstract class WebModelContext : DbContext
{
public WebModelContext()
: base("WebConnection")
{
Configuration.LazyLoadingEnabled = true;
}
}
這是我的上下文類,它繼承了我的WebModelContext
類:
public class AccountContext : WebModelContext
{
private DbSet<User> _users;
public AccountContext()
: base()
{
_users = Set<User>();
}
public DbSet<User> Users
{
get { return _users; }
}
}
這是我的存儲庫類:
public abstract class IRepository<T> : IDisposable where T : WebModelContext, new()
{
private T _context;
protected T Context
{
get { return _context; }
}
public IRepository() {
_context = new T();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~IRepository()
{
Dispose(false);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (_context != null)
{
_context.Dispose();
_context = null;
}
}
}
}
這是我AccountRepository類:
public class AccountRepository : IRepository<AccountContext>
{
public List<User> GetUsers()
{
return Context.Users.ToList();
}
public User GetUser(string username)
{
return Context.Users.Where(u => u.Name == username).FirstOrDefault();
}
public User CreateUser(string username, string password, string salt, int age, int residence)
{
User user = new User
{
Name = username,
Password = password,
Salt = salt,
RoleId = 1,
CreatedOn = DateTime.Now,
Locked = false,
Muted = false,
Banned = false,
Guid = Guid.NewGuid().ToString("N")
};
Context.Users.Add(user);
return Context.SaveChanges() > 0 ? user : null;
}
}
任何幫助,不勝感激:)
感謝您的幫助,我試圖做這剛剛和我遇到了同樣的錯誤。我最初添加了你的代碼,但VS說它不覆蓋從DbContext的OnModelCreating,所以我用覆蓋取代了虛擬。這樣做後,我添加了一個斷點'modelBuilder.Entity();'但它沒有達到斷點,仍然給出了相同的錯誤。 –
@SHTester嘗試停止並啓動本地ASP.NET開發服務器/ IIS – Eranga
好了,仍然是同樣的錯誤,我會嘗試重新啓動機器。 –