简体   繁体   English

关系对象映射C#

[英]Relational object mapping c#

What is the best way to map relational table which has more than 150 columns. 映射具有超过150列的关系表的最佳方法是什么。 I don't want to use any 3rd party or entity framework. 我不想使用任何第三方或实体框架。 if i am using data-reader it is very hard to write all the columns and convert it to relevant type. 如果我使用数据读取器,则很难编写所有列并将其转换为相关类型。

Is there any easy way to do it or is this the only way? 有没有简单的方法可以做到这一点,或者这是唯一的方法吗?

 SqlDataReader _dr = _sqlCom.ExecuteReader() ;

        Info inObj= new Info ();


        while (_dr.Read())
        {

            inObj.a=  (int)_dr["a"];
            inObj.b= (int)_dr["b"];
            inObj.c= (int)_dr["c"];
            inObj.d= (int)_dr["d"];
            inObj.e= (int)_dr["e"];
            .....

            ......
        }

You could use reflection, if you're OK with incurring the performance hit. 如果可以接受性能下降,可以使用反射。 Something like this should work: 这样的事情应该起作用:

SqlDataReader reader = ...;
var propertyMappings = typeof (Info).GetProperties(BindingFlags.Instance | BindingFlags.Public)
    .Select(p => new {Property = p, Ordinal = reader.GetOrdinal(p.Name)})
    .ToList();
while (reader.Read())
{
    var info = new Info();
    foreach (var propertyMapping in propertyMappings)
        propertyMapping.Property.SetValue(info, reader[propertyMapping.Ordinal]);
}

If you want it done for you, you'll need to either use an ORM, there are some good ones out there, like Dapper , or use reflection (but will be slower). 如果您想为自己完成任务,则需要使用ORM,那里有一些不错的工具,例如Dapper ,或者使用反射(但会慢一些)。 Otherwise you need to handle it all yourself. 否则,您需要自己处理。 However instead of the ugly casting, you could write a few more lines of code to get rid of the casting, and would probably perform better 但是,除了丑陋的强制转换之外,您还可以编写几行代码来摆脱强制转换,并且可能会更好地执行

SqlDataReader _dr = _sqlCom.ExecuteReader() ;


Info inObj = new Info();

if (!_dr.HasRows) { return; }

int aPosition = _dr.GetOrdinal("a");}
int bPosition = _dr.GetOrdinal("b");
int cPosition = _dr.GetOrdinal("c");
int dPosition = _dr.GetOrdinal("d");
int ePosition = _dr.GetOrdinal("e");

while (_dr.Read())
{
    inObj.a = _dr.GetInt32(aPosition);
    inObj.b = _dr.GetInt32(bPosition);
    inObj.c = _dr.GetInt32(cPosition);
    inObj.d = _dr.GetInt32(dPosition);
    inObj.e = _dr.GetInt32(ePosition);

    .....

    ......
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM