EF 4.1代码首先仍然在寻找不再存在的旧表

时间:2011-08-16 12:38:58

标签: entity-framework entity-framework-4 entity-framework-4.1

我首先使用Entity Framework 4.1代码。

我在数据库中有一个名为MaritalStatus的表。我删除了它并在其名为MaritalStatuses的位置创建了一个新表。每当我尝试从表中获取所有记录时,我都会收到错误:

无效的对象名称'dbo.MaritalStatus'。

它正在尝试执行的查询是:

SELECT 
[Extent1].[Id] AS [Id], 
[Extent1].[Name] AS [Name], 
[Extent1].[IsActive] AS [IsActive]
FROM [dbo].[MaritalStatus] AS [Extent1]}

为什么还要查找我删除的表MaritalStatus?有可能它被缓存在某个地方吗?我删除了整个数据库并通过脚本重新创建它。仍然没有运气。也许它涉及名称的“es”部分有问题?

上下文类:

public class HefContext : DbContext
{
   public DbSet<Bank> Banks { get; set; }
   public DbSet<AccountType> AccountTypes { get; set; }
   public DbSet<MaritalStatus> MaritalStatuses { get; set; }
}

查看模型(具有部分属性):

public class EditGrantApplicationViewModel
{
   public int Id { get; set; }
   public string EmployeeNumber { get; set; }
   public string FirstName { get; set; }
   public string LastName { get; set; }
   public int MaritalStatusId { get; set; }
   public IEnumerable<MaritalStatus> MaritalStatuses { get; set; }
   public int BankId { get; set; }
   public IEnumerable<Bank> Banks { get; set; }
   public int AccountTypeId { get; set; }
   public IEnumerable<AccountType> AccountTypes { get; set; }
}

MaritalStatuses视图中的下拉列表:

<td><label>Marital Status:</label> <span class="red">**</span></td>
<td>
   @Html.DropDownListFor(x => x.MaritalStatusId, new SelectList(Model.MaritalStatuses, "Id", "Name", Model.MaritalStatusId), "-- Select --")
   @Html.ValidationMessageFor(x => x.MaritalStatusId)
</td>

控制器:

public ActionResult Create()
{
   EditGrantApplicationViewModel viewModel = new EditGrantApplicationViewModel
   {
      MaritalStatuses = maritalStatusService.GetAll(),
      Banks = bankService.GetAll(),
      AccountTypes = accountTypeService.GetAll()
   };

   return View(viewModel);
}

服务:

public IEnumerable<MaritalStatus> GetAll()
{
   return maritalStatusRepository.GetAll();
}

存储库:

HefContext db = new HefContext();

public IEnumerable<MaritalStatus> GetAll()
{
   return db.MaritalStatuses;
}

模特课:

public class MaritalStatus
{
   public int Id { get; set; }
   public string Name { get; set; }
   public bool IsActive { get; set; }
}

2 个答案:

答案 0 :(得分:2)

您可能已在数据库中重命名该表,但您的Model类仍与旧名称绑定。您需要在DbContext对象的OnModelCreating方法中将实体映射到所需的表名称

public class HefContext : DbContext
{
   public DbSet<Bank> Banks { get; set; }
   public DbSet<AccountType> AccountTypes { get; set; }
   public DbSet<MaritalStatus> MaritalStatuses { get; set; }
   protected override void OnModelCreating(DbModelBuilder modelBuilder)
   {
       modelBuilder.Entity<MaritalStatus>().ToTable("MaritalStatuses");
   }
}

<强>更新

显然,EF代码首先在某些表名称的复数形式方面存在一些问题,例如Status。出于好奇,我测试了其他几个,发现了几个也有同样问题。

答案 1 :(得分:-2)

我想这是错的:

public DbSet<MaritalStatus> MaritalStatuses { get; set; }

应该是:

public DbSet<MaritalStatuses> MaritalStatuses { get; set; }