I need to project integer values from a database into enumeration values using Entity Framework and AutoMapper. It seems that the problems are that the columns can be nullified in some cases and cannot be nullified in other cases. If they are of type with a null value, I want to use the default value (the first value of the enumeration) for zeros.
Here is a complete, minimal example that I used with my current approach. This is a console application with the current Nuget Entity Framework and AutoMapper packages. It also needs a database (first for the database) with the following table:
CREATE TABLE [dbo].[MyTable] (
[Id] INT PRIMARY KEY,
[EnumValue] INT NOT NULL,
[EnumValueNullable] INT
)
Code for console application (C #):
public enum MyEnum
{
Value1 = 0,
Value2 = 1
}
public class MyTableModel
{
public int Id { get; set; }
public MyEnum EnumValue { get; set; }
public MyEnum EnumValueNullable { get; set; }
}
public class MyProfile : Profile
{
public MyProfile()
{
this.CreateMap<MyTable, MyTableModel>();
this.CreateMap<int, MyEnum>().ProjectUsing(x => (MyEnum)x);
this.CreateMap<int?, MyEnum>().ProjectUsing(x => x.HasValue ? (MyEnum)x.Value : MyEnum.Value1);
}
}
static void Main(string[] args)
{
var config = new MapperConfiguration(x => x.AddProfile(new MyProfile()));
var result = new MyDataEntities().MyTable.ProjectTo<MyTableModel>(config).ToList();
}
, HasValue System.Int32.
, , , , AutoMapper , , NULL.
( int int?) , .
, AutoMapper 3.3.1.0 .
, , .