抛砖引玉

最近在一个项目中要用到WEBSERVICE传递LINQ对象列表.但直接传递IList<TEntity>是没有办法序列化这样的复杂对象的.
[或许可以,我自已没有吃透]

所以写了下面一段代码把IList<TEntity>转化为DataSet对象来传...(尽管对性能上有待商榷,但也不失为一个方法)
代码如下:

public static class MyCustomExtensions
    
{
        
public static DataTable ToDataTable<TEntity>(this IList<TEntity> list) where TEntity : IMyCustomObject
        
{
            Type type 
= typeof(TEntity);
            System.Reflection.PropertyInfo[] infos 
= type.GetProperties();
            DataTable dt 
= new DataTable();
            ArrayList al 
= new ArrayList();
            
foreach (System.Reflection.PropertyInfo info in infos)
            
{
                
if (info.GetCustomAttributes(typeof(System.Data.Linq.Mapping.ColumnAttribute), false).Length > 0)
                
{
                    dt.Columns.Add(info.Name, info.PropertyType);
                    al.Add(info.Name);
                }

            }


            
if (al.Count < 1)
                
return null;

            
foreach (TEntity obj in list)
            
{
                DataRow row 
= dt.NewRow();
                
foreach (string columnName in al)
                
{
                    row[columnName] 
= type.GetProperty(columnName).GetValue(obj, null);
                }

                dt.Rows.Add(row);
            }

            
return dt;
        }

    }
//就只是作约束来用
public interface ICustomObject{}
//局部类中继承这个接口,User是Linq对象
//如果使用dbml来生成Linq代理的朋友这样的好处是设计视图时不会被椱盖掉
public partial class User : IGansoObject{}

到此为止,我们的IList<User>对象就可以使用ToDataTable()这个方法了.
如:
MyDBContext.Instance().Users.Where(u => u.EMail.IndexOf("a")!=-1).ToList().ToDataTable();

以上代码纯是抛砖引玉.我也期待更好的方法.请与我联系:-)

原文地址:https://www.cnblogs.com/apexchu/p/1222628.html