使用枚举器进行映射
本文关键字:映射 枚举 | 更新日期: 2023-09-27 18:28:34
我有一个带有一列char(2)的表
CREATE TABLE COMPANY (
EMP_ID INTEGER NOT NULL,
EMP_TYPE CHAR(2) NOT NULL,
EMP_NM VARCHAR(35) NOT NULL
);
使用实体框架,我想用枚举映射实体。
public class Company
{
public Company ()
{
Id = null;
Type = Enums.EnumType.TipoCompany.Matriz;
Name = string.Empty;
}
public int? Id{ get; set; }
public string Name{ get; set; }
public Enums.EnumType.TipoCompany TipoCompany { get; set; }
}
public class CompanyMap : EntityTypeConfiguration<Company>
{
public CompanyMap()
{
ToTable("COMPANY");
HasKey(t => new { t.Id});
Property(t => t.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None).HasColumnName("EMP_ID");
Property(t => t.Name)
.IsRequired()
.HasMaxLength(35)
.HasColumnType("Varchar")
.HasColumnName("EMP_NM");
Property(t => t.TypeCompany)
.IsRequired()
.HasColumnType("Varchar")
.HasColumnName("EMP_TYPE");
}
}
public class EnumTypeCompany
{
public enum TypeCompany
{
[Description("Matriz")]
Matriz = 01,
[Description("Filial")]
Filial = 02,
}
}
我得到错误:
Contexto.Type[Nullable=False,DefaultValue=]' of member 'TypoCompany' in type 'Contexto.Company' is not compatible with 'FirebirdClient.varchar
如何将varchar转换为枚举???
如果在EMP_TYPE字段中使用int而不是varchar,则问题应该得到解决。当您从数据库中获取数据时,int字段将自动转换到您的枚举中。
更新
public class Company
{
public Company ()
{
Id = null;
TipoCompanyString = ((int)Enums.EnumType.TipoCompany.Matriz).ToString();
TipoCompany = Enums.EnumType.TipoCompany.Matriz;
Name = string.Empty;
}
public int? Id { get; set; }
public string Name { get; set; }
public string TipoCompanyString { get; set; }
public Enums.EnumType.TipoCompany TipoCompany {
get {
var intValue = Convert.ToInt32(TipoCompanyString);
return (Enums.EnumType.TipoCompany)intValue;
}
set {
TipoCompanyString = ((int)value).ToString()
}
}
}
public class CompanyMap : EntityTypeConfiguration<Company>
{
public CompanyMap()
{
ToTable("COMPANY");
HasKey(t => new { t.Id});
Property(t => t.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None).HasColumnName("EMP_ID");
Property(t => t.Name)
.IsRequired()
.HasMaxLength(35)
.HasColumnType("Varchar")
.HasColumnName("EMP_NM");
Property(t => t.TipoCompanyString)
.IsRequired()
.HasColumnType("Varchar")
.HasColumnName("EMP_TYPE");
}
}
public class EnumTypeCompany
{
public enum TypeCompany
{
[Description("Matriz")]
Matriz = 01,
[Description("Filial")]
Filial = 02,
}
}
在c#中,不能有enum:string
,只能有int
、byte
等。您可以做的是制作一个"伪"枚举:
public static class FakeEnum
{
public static readonly OptionOne = "blabla";
public static readonly OptionTwo = "random";
}
字符串值将是数据库中EMP_TYPE
字段的值。您可以像使用字符串枚举一样使用它,例如在checks:中
Company company = db.Companies.First();
if(company.Type == FakeEnum.OptionOne) //company.Type is really "blabla" in db
DoStuff();