映射到已经存在的数据库表 [英] Mapping to already existing database table
问题描述
我正在使用实体框架4.1代码第一个
连接到已经存在的数据库。我先使用的表称为 Bank
。我也有一个银行类
作为我的域模型。这是我如何映射我的类和表:
I am using Entity Framework 4.1 code first
to connect to an already existing database. The table that I am using first is called Bank
. I also have a Bank class
as my domain model. This is how I mapped my class and table:
public class HbfContext : DbContext
{
public DbSet<Bank> Banks { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Bank>().ToTable("Bank");
}
}
我的银行表:
BankID INT
BankName VARCHAR(50)
我的银行类看起来像这样:
My Bank class looks like this:
public class Bank
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsActive { get; set; }
}
当我要退回所有银行时,我遇到问题。返回的SQL语句:
I am having issues when I want to return all the banks. The SQL statement returned from:
return db.Banks
.OrderBy(x => x.Name);
是:
SELECT
[Extent1].[Id] AS [Id],
[Extent1].[Name] AS [Name],
[Extent1].[IsActive] AS [IsActive]
FROM
[dbo].[Bank] AS [Extent1]
ORDER BY
[Extent1].[Name] ASC
这不会工作,因为我的表没有Id,Name和IsActive列。我将如何解决这个问题,并且将EFB将BankId映射到Id和BankName以自动命名?
This is not going to work because my table does not have the Id, Name and IsActive columns. How would I fix this and would EF map BankId to Id and BankName to Name automatically?
推荐答案
您需要指示EF忽略 IsActive
属性并映射其他属性。如果您不喜欢数据注释,您可以使用流畅的API来执行此操作:
You need to instruct EF to ignore IsActive
property and map other properties. If you don't like data annotations you can do this with fluent API:
modelBuilder.Entity<Bank>().Ignore(b => b.IsActive);
modelBuilder.Entity<Bank>().Property(b => b.Id).HasColumnName("BankID");
modelBuilder.Entity<Bank>().Property(b => b.Name).HasColumnName("BankName");
这篇关于映射到已经存在的数据库表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!