简体   繁体   English

Linq2sql泛型按列和值选择

[英]Linq2sql Generics select by column and value

I am using generics to do some basic insert/updates/selects from a database using linq2sql. 我正在使用泛型使用linq2sql从数据库中进行一些基本的插入/更新/选择。

I have the following and im trying to convert it to take in a column name and an object value to select based off but im not able to get it to work. 我有以下内容,即时通讯试图将其转换为采用列名和对象值进行选择,但即时通讯无法正常工作。

public static T SelectByID<T>(string id) where T : class
{
    try
    {
        using (DataContext db = new DataContext(CHCGlobal.ConnectionString))
        {
            //get Table of type T
            var table = db.GetTable<T>();

            //get object mappings
            MetaModel modelMap = table.Context.Mapping;

            //get the data members for this type
            ReadOnlyCollection<MetaDataMember> dataMembers = modelMap.GetMetaType(typeof(T)).DataMembers;

            //find primary key
            string pk = (dataMembers.Single<MetaDataMember>(m => m.IsPrimaryKey)).Name;

            //return a single object with the id matching the pk field
            return table.SingleOrDefault<T>(delegate (T t)
            {
                string memberId = t.GetType().GetProperty(pk).GetValue(t, null).ToString();
                return memberId.ToString() == id.ToString();
            });
        }
    }
    catch (Exception)
    {
        throw;
    }
}

This is the function im trying to create but im getting stuck on the select statement. 这是我试图创建的函数,但我被卡在了select语句上。

public static List<T> SelectByKeyValue<T>(string id, object value) where T : class
{
    try
    {
        using (DataContext db = new DataContext(CHCGlobal.ConnectionString))
        {
            //get Table of type T
            var table = db.GetTable<T>();

            //get object mappings
            MetaModel modelMap = table.Context.Mapping;

            //get the data members for this type
            ReadOnlyCollection<MetaDataMember> dataMembers = modelMap.GetMetaType(typeof(T)).DataMembers;

            //find key
            string pk = (dataMembers.Single<MetaDataMember>(m => m.Name.Equals(id))).Name;

            //NOT WORKING
            return table.Select<T, T>(delegate (T t)
            {
                var memberID = t.GetType().GetProperty(pk).GetValue(t, null);
                return memberID.Equals(value);
            }).ToList<T>();
        }
    }
    catch (Exception)
    {
        throw;
    }
}

You have to use Where , not Select . 您必须使用Where而不是Select

Select transforms N items into N new items, it doesn't filter. Select将N个项目转换为N个新项目,但不进行过滤。
Where does that. Where

return table.Where(t => t.GetType().GetProperty(pk).GetValue(t, null)
                         .Equals(value))
            .ToList();

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

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