Bre*_*ogt 9 c# entity-framework entity-framework-5
我正在使用Entity Framework 5 - Code.
我有一个数据库,我连接到已经存在一段时间了(我没有创建它).有一张叫做的桌子T_Customers.它包含所有客户的列表.它具有以下结构(仅部分显示):
Customer_id | numeric (5, 0) | auto increment | not null (not set as primary key)
FName | varchar(50) | not null
LName | varchar(50) | not null
Run Code Online (Sandbox Code Playgroud)
我的Customer班级:
public class Customer : IEntity
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我的IEntity界面:
public interface IEntity
{
int Id { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我在我的数据库上下文类中有以下内容:
public class DatabaseContext : DbContext
{
public DatabaseContext(string connectionString)
: base(connectionString)
{
}
public DbSet<Customer> Customers { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new CustomerConfiguration());
}
public new DbSet<TEntity> Set<TEntity>()
where TEntity : class, IEntity
{
return base.Set<TEntity>();
}
}
Run Code Online (Sandbox Code Playgroud)
我的客户配置类:
class CustomerConfiguration : EntityTypeConfiguration<Customer>
{
internal CustomerConfiguration()
{
this.ToTable("T_Customers");
this.Property(x => x.Id).HasColumnName("Customer_id");
this.Property(x => x.FirstName).HasColumnName("FName");
this.Property(x => x.LastName).HasColumnName("LName");
}
}
Run Code Online (Sandbox Code Playgroud)
我试图在我的实体声明中保持一致,我需要所有的ID都是整数.此客户ID在数据库中的类型为numeric,现在我在尝试返回所有客户的列表时遇到问题.如何从数据库数字类型映射到C#整数类型?我没有将我的类ID改为可空或十进制,我的ID总是不可为空和整数.我也无法更改数据库.
我得到的错误是:
The 'Id' property on 'Customer' could not be set to a 'Decimal' value.
You must set this property to a non-null value of type 'Int32'.
Run Code Online (Sandbox Code Playgroud)
为列指定数字类型
Property(x => x.Id).HasColumnName("Customer_id").HasColumnType("numeric");
Run Code Online (Sandbox Code Playgroud)
生成数据库时,它将精确创建数字列18,0.但是当您映射到现有数据库时,它将适用于5,0数字列.