lundi 7 novembre 2016

How to get as Func

There are many classes in my project so I dont want to make a definition like below for every class.

    private static Func<IDataReader, User> Make = reader => new User
    {
        Id = reader["Id"].AsId(),
        UniqueId = reader["UniqueId"].AsGuid(),
        Name = reader["Name"].AsString(),
        Email = reader["Email"].AsString(),
        LanguageId = reader["LanguageId"].AsInt(),
        CompanyInfoId = reader["CompanyInfoId"].AsInt(),
        UserTypeId = reader["UserTypeId"].AsInt(),
        InsertedBy = reader["InsertedBy"].AsInt(),
        InsertedOn = reader["InsertedOn"].AsDateTime(),
        UpdatedBy = reader["UpdatedBy"].AsInt(),
        UpdatedOn = reader["UpdatedOn"].AsDateTime(),
        DeletedBy = reader["DeletedBy"].AsInt(),
        DeletedOn = reader["DeletedOn"].AsDateTime(),
        IsDeleted = reader["IsDeleted"].AsBool(),
    };

How to make a generic definition for my classes with reflection.

    var result = db.Read<User>(sql, **Make**, new { id = id }).SingleOrDefault();

-

    public IEnumerable<T> Read<T>(string sql, Func<IDataReader, T> make, params object[] parms)
    {
        using (var connection = CreateConnection())
        {
            using (var command = CreateCommand(sql, connection, parms))
            {
                using (var reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        yield return make(reader);
                    }
                }
            }
        }
    }

I looked at Stackoverflow, found a sample. I wasn't sure how do I do that.

Sorry my bad english.





Aucun commentaire:

Enregistrer un commentaire