简体   繁体   English

遍历强类型字段Entity Framework c#

[英]Loop through strongly type fields Entity Framework c#

I am trying to come up with a neat solution for this problem to make it scalable. 我正在尝试针对此问题提出一个整洁的解决方案,以使其可扩展。 I've got a DataTable dt, which has its structure read from a database. 我有一个DataTable dt,它的结构是从数据库中读取的。 I want to be able to correctly map this data into the correct fields using Entity Framework and allow the code to function even if columns are added or deleted. 我希望能够使用Entity Framework将这些数据正确映射到正确的字段中,并且即使添加或删除列也能使代码起作用。

using (Entities db = new Entities())
{
    foreach (DataRow dr in dt.Rows)
    {
        var result = db.myTable.SingleOrDefault(e => e.Email == dr["Email"].ToString());

        foreach (SourceToDestinationMapping s in mapping)
        {
            // want to do something like this
            result[s.DestinationColumn] = dt[s.DestinationColumn];

           // instead of this
           result.Name = dt["Name"].ToString();
           result.Address = dt["Address"].ToString();
           // all field mappings
        }
    }
}

Is this something that is possible to do? 这可能吗? Or do I need to make code changes every time a new column gets added/removed? 还是每次添加/删除新列时都需要更改代码? If this isn't something that works then I can switch to doing something like this without Entity Framework. 如果这不起作用,那么我可以在没有Entity Framework的情况下切换到类似的方式。

Edit: 编辑:

Example would be: 1, EmailAddress, Email, 1 示例为:1,EmailAddress,Email,1

public partial class SourceToDestinationMapping
{
    public int MappingId { get; set; }
    public string SourceColumn { get; set; }
    public string DestinationColumn { get; set; }
    public bool Active { get; set; }
}

Since Entity Framework works with objects you'd need to use reflection to get and set properties without knowing which properties you need to operate on, and it can get pretty complicated if you have many types that you need to handle. 由于Entity Framework与对象一起使用,因此您需要使用反射来获取和设置属性,而又不知道需要对哪些属性进行操作,如果您需要处理许多类型,则它可能变得非常复杂。 So basically examine the type of the object you're looking at, get its list of properties, and search for columns with the same name as the property (or some other convention you have) in the data table row. 因此,基本上检查一下您要查看的对象的类型,获取其属性列表,并在数据表行中搜索与该属性同名(或您拥有的其他约定)的列。 But again, you'll need to handle the type conversions, if the property is an int you need to get the cell value as an int etc. 但是同样,您将需要处理类型转换,如果属性是int,则需要将单元格值作为int等获取。

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

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