Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将两个方法合并为一个泛型方法_C#_Linq To Sql - Fatal编程技术网

C# 将两个方法合并为一个泛型方法

C# 将两个方法合并为一个泛型方法,c#,linq-to-sql,C#,Linq To Sql,我的DAL中有两个相同的方法,它们基于作为参数提供的主键返回数据库行。数据库上下文是linqtoSQL。一个传入字符串参数,第二个传入int参数。我认为必须使用泛型来创建一个接受string或int但不确定如何接受的方法 /// <summary> /// Select table row by integer Primary Key Value /// </summary> /// <typeparam name="T">&l

我的DAL中有两个相同的方法,它们基于作为参数提供的主键返回数据库行。数据库上下文是linqtoSQL。一个传入字符串参数,第二个传入int参数。我认为必须使用泛型来创建一个接受string或int但不确定如何接受的方法

    /// <summary>
    /// Select table row by integer Primary Key Value
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="id">The PK value to search for</param>
    /// <returns>Single matching PK to id</returns>
    public T SelectRowByPk<T>(int id) where T : class
    {
        using (var dc = new DBDataContext())
        {
            // Get the table by the type passed in
            var table = dc.GetTable<T>();
            // Get the metamodel mappings (database to domain objects)
            MetaModel modelMap = table.Context.Mapping;
            // Get the data members for this type
            ReadOnlyCollection<MetaDataMember> dataMembers =  
            modelMap.GetMetaType(typeof (T)).DataMembers;
            // Find the primary key field name by checking for IsPrimaryKey
            string pk = (dataMembers.Single(m => m.IsPrimaryKey)).Name;

            // Return a single object where the id argument matches the primary key 
            field value
            return table.SingleOrDefault(delegate(T t)
                                            {
                                                int memberId =

  Convert.ToInt16(t.GetType().GetProperty(pk).GetValue(t, null));
                                                return memberId == id;
                                            });
        }
    }

    /// <summary>
    /// Select table row by Varchar Primary Key Value
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="id">The PK value to search for</param>
    /// <returns>Single matching PK to id</returns>
    public T SelectRowByVarcharPk<T>(string id) where T : class
    {
        using (var dc = new DBDataContext())
        {
            // Get the table by the type passed in
            var table = dc.GetTable<T>();
            // Get the metamodel mappings (database to domain objects)
            MetaModel modelMap = table.Context.Mapping;
            // Get the data members for this type
            ReadOnlyCollection<MetaDataMember> dataMembers = 
  modelMap.GetMetaType(typeof(T)).DataMembers;
            // Find the primary key field name by checking for IsPrimaryKey
            string pk = (dataMembers.Single(m => m.IsPrimaryKey)).Name;

            // Return a single object where the id argument matches the primary key 
 field value
            return table.SingleOrDefault(delegate(T t)
            {
                string memberId =
                   t.GetType().GetProperty(pk).GetValue(t, null).ToString();
                return memberId == id;
            });
        }
    }

指定类型参数的要点之一是,这样就可以拥有动态参数类型。在本例中,“id”将成为您指定的任何类型。

您不能直接使用泛型将两个方法合并为一个,但是您可以结合泛型使用一点重构来获得干净的设计:

创建一个私有方法,使用两个通用参数执行繁重的工作,一个用于实体类型,另一个用于主键类型:

 private T SelectRowById<T, TId>(TId id) where T : class
    {
        using (var dc = new DBDataContext())
        {
            // Get the table by the type passed in
            var table = dc.GetTable<T>();
            // Get the metamodel mappings (database to domain objects)
            MetaModel modelMap = table.Context.Mapping;
            // Get the data members for this type
            ReadOnlyCollection<MetaDataMember> dataMembers = 
  modelMap.GetMetaType(typeof(T)).DataMembers;
            // Find the primary key field name by checking for IsPrimaryKey
            string pk = (dataMembers.Single(m => m.IsPrimaryKey)).Name;

            // Return a single object where the id argument matches the primary key 
 field value
            return table.SingleOrDefault(delegate(T t)
            {
                var memberId =
                   (TId)t.GetType().GetProperty(pk).GetValue(t, null);
                return memberId == id;
            });
        }
    }
在此之后,可以为使用此私有方法的特定id类型声明两个公共方法:

public T SelectRowById<T>(string id) where T : class
{
   return SelectRowById<T, string>(id);
}

public T SelectRowById<T>(int id) where T : class
{
   return SelectRowById<T, int>(id);
}
通过这种方式,您将拥有一个干净的公共界面,代码重复最少

public T SelectRowById<T>(string id) where T : class
{
   return SelectRowById<T, string>(id);
}

public T SelectRowById<T>(int id) where T : class
{
   return SelectRowById<T, int>(id);
}