具有模型中具有不同名称和类型的属性的Dapper映射列



我有一个模型,这个模型是:

 public class Member
    {
        #region public property
        public int Id { get; set; }
        public string LastName { get; set; }
        public string FirstName { get; set; }
        public AccountState AccountState { get; set; }
        public GodFatherType GodFatherType { get; set; }
}

AccountState和GodFatherType都是两个独立的:

 public enum AccountState 
{
    NotActivated = 0,
    Activated = 1,
    Desactived = 2,
}
 public enum GodFatherType
    {
        Undefined=0,
        unknown = 1,
        Correct = 2,
    }

在数据库中,我有Id、LastName、FistName、TinyInt AccountstateId和smallint GodFatherTypeid,我不想更改我的存储过程。如何将我的类Member映射到数据库??

事实上,当我用以下代码执行存储过程时,我只得到属性only Id,LastName,FistName:

 public sealed class DbContext : IDbContext
{
    private bool disposed;
    private SqlConnection connection;
    public DbContext(string connectionString)
    {
        connection = new SqlConnection(connectionString);
    }
    public IDbConnection Connection
    {
        get
        {
            if (disposed) throw new ObjectDisposedException(GetType().Name);
            return connection;
        }
    }
    public IDbTransaction CreateOpenedTransaction()
    {
        if (connection.State != ConnectionState.Open)
            Connection.Open();
        return Connection.BeginTransaction();
    }
    public IEnumerable<T> ExecuteProcedure<T>(string procedure, dynamic param = null, IDbTransaction transaction = null)
    {
        if (connection.State == ConnectionState.Closed)
        {
            connection.Open();
        }
        return Dapper.SqlMapper.Query<T>(connection, procedure, param, transaction,
            commandType: CommandType.StoredProcedure);
    }
    public int ExecuteProcedure(string procedure, dynamic param = null, IDbTransaction transaction = null)
    {
        if (connection.State == ConnectionState.Closed)
        {
            connection.Open();
        }
        return Dapper.SqlMapper.Execute(connection, procedure, param, transaction,
            commandType: CommandType.StoredProcedure);
    }
    public void Dispose()
    {
        Debug.WriteLine("** Disposing DbContext");
        if (disposed) return;
        if (connection != null)
        {
            connection.Dispose();
            connection = null;
        }
        disposed = true;
    }
}

最简单的选项是将它们保持为1:1,即

public AccountState AccountStateId { get; set; }
public GodFatherType GodFatherTypeId { get; set; }

其中

public enum AccountState : byte {...}
public enum GodFatherType : short {...}

如果无法重命名属性,可以添加填充程序属性:

private byte AccountStateId {
    get { return (byte)(int)AccountState; }
    set { return AccountState = (AccountState)(int)value; }
}

也可以重命名映射中的成员,但这更复杂。

相关内容

  • 没有找到相关文章

最新更新