Tôi đang cố gắng cập nhật kho lưu trữ của mình lên EF5 nhưng đã gặp phải một vài lỗi. Tôi đã xem xét xung quanh stackoverflow cho các lỗi tương tự phát hiện ra một vài câu hỏi/câu trả lời nhưng tiếc là cùng một câu trả lời đã không giải quyết được vấn đề của tôi.Loại thực thể không phải là một phần của mô hình, EF 5
Đây là lỗi của tôi:
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.
Đây là lớp DbContext tôi:
public abstract class WebModelContext : DbContext
{
public WebModelContext()
: base("WebConnection")
{
Configuration.LazyLoadingEnabled = true;
}
}
Đây là lớp bối cảnh của tôi mà được thừa hưởng WebModelContext
lớp học của tôi:
public class AccountContext : WebModelContext
{
private DbSet<User> _users;
public AccountContext()
: base()
{
_users = Set<User>();
}
public DbSet<User> Users
{
get { return _users; }
}
}
Đây là của tôi lớp lưu trữ:
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;
}
}
}
}
Đây là lớp AccountRepository tôi:
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;
}
}
Bất kỳ trợ giúp đánh giá rất cao :)
Thanks for the help, tôi đã cố gắng làm điều này ngay bây giờ và tôi gặp phải lỗi tương tự. Ban đầu tôi đã thêm mã của bạn nhưng VS cho biết nó không ghi đè OnModelCreating từ DbContext nên tôi đã thay thế ảo bằng ghi đè. Sau khi thực hiện điều đó, tôi đã thêm một breakpoint vào dòng 'modelBuilder.Entity();' nhưng nó không đạt đến điểm ngắt và vẫn cho cùng một lỗi. –
@SHTester Hãy thử dừng và khởi động máy chủ phát triển ASP.NET cục bộ/IIS – Eranga
được rồi, vẫn còn lỗi tương tự, tôi sẽ thử khởi động lại máy. –