Gau*_*aui 35 entity-framework asp.net-mvc-4
我正在使用EF Code-First到现有的数据库方法,并IsActive在我的数据库中有一个字段.问题是该领域VARCHAR应该是什么时候boolean.我无法更改数据库架构.
数据库中的示例值为"Y" (true)或"N" (false)
映射时,我想将这些值转换为true/false,并使我的Entity类保持布尔值.
这可能吗?
我的实体和映射类如下,但我想将该IsActive字段更改为布尔值.
public class Employee
{
public int ID { get; set; }
public string SSN { get; set; }
public string Email { get; set; }
public string IsActive { get; set; }
}
public class EmployeeMap : EntityTypeConfiguration<Employee>
{
public EmployeeMap()
{
this.ToTable("Employees");
this.HasKey(t => t.ID);
this.Property(t => t.ID).HasColumnName("ID_Employee");
this.Property(t => t.SSN).HasColumnName("sReference");
this.Property(t => t.Email).HasColumnName("Email");
this.Property(t => t.IsActive).HasColumnName("IsActive");
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:我找不到其他解决方案:https://stackoverflow.com/a/6709186/1053611
Col*_*lin 43
正如其他人指出你需要两个属性,但你可能有兴趣知道你可以将其中一个属性设为私有,并仍然将其映射到数据库:
private string isActive { get; set; }
[System.ComponentModel.DataAnnotations.Schema.NotMapped]
public bool IsActive
{
get { return isActive == "Y"; }
set { isActive = value ? "Y" : "N"; }
}
Run Code Online (Sandbox Code Playgroud)
如果您使用的是EF6,则可以在OnModelCreating方法中使用自定义约定来映射私有属性
modelBuilder.Types().Configure(c =>
{
//NB the syntax used here will do this for all entities with a
//private isActive property
var properties = c.ClrType.GetProperties(BindingFlags.NonPublic
| BindingFlags.Instance)
.Where(p => p.Name == "isActive");
foreach (var p in properties)
c.Property(p).HasColumnName("IsActive");
});
Run Code Online (Sandbox Code Playgroud)
参考文献:
编辑:
这是识别应映射到数据库的私有属性的另一种方法:
首先将列属性添加到私有属性:
[System.ComponentModel.DataAnnotations.Schema.Column]
private string isActive { get; set; }
Run Code Online (Sandbox Code Playgroud)
然后使用该属性的存在来标识OnModelCreating方法中的私有属性:
modelBuilder.Types().Configure(c =>
{
var properties = c.ClrType
.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance)
.Where(propInfo =>
propInfo.GetCustomAttributes(typeof(ColumnAttribute), true).Length > 0);
foreach (var p in properties)
c.Property(p).HasColumnName(p.Name);
});
Run Code Online (Sandbox Code Playgroud)
参考:使用实体框架映射私有属性
| 归档时间: |
|
| 查看次数: |
27752 次 |
| 最近记录: |