简体   繁体   中英

c# Derived Class issue

At the bottom of this message is a class and controller for that class. I have to do this for a couple hundred SQL tables. Yeah.

What I'd like to do is to be able to use a more generic base controller such that a specific controller would be something like:

public class IMS_ProductController : IMS_BaseController

    public IEnumerable<IMS_Table> _recordset {get; set;}
    string _tablename = "IMS_Product";
    string _keyname = "ProductID";
}

and my base contoller would be like the IMS_ProductController below.

The issue is the first line above. How to I take care of _recordset and more specifically, <IMS_Table> which will be different for each of the SQL tables. You can see in the controller below (which, again, I'd like to turn into a generic controller) that I do things like:

var table = new List<IMS_Table>();
or
IMS_Table t = new IMS_Table();

Things like that.

Any suggestions would be incredibly helpful.

Thank you! Chris

namespace IMS.Model
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.Reflection;
using System.Linq;
//using System.Runtime.Serialization.Formatters.Binary;

[AttributeUsage(AttributeTargets.Property, Inherited = true)]
[Serializable]
public class MappingAttribute : Attribute
{
    public string ColumnName = null;
}

public class IMS_Product
{
    [Mapping(ColumnName = "ProductID")]
    [Key]
    public Guid ProductId { get; set; }

    [Mapping(ColumnName = "Name")]
    [Required]
    public string Name { get; set; }

    [Mapping(ColumnName = "Description")]
    public string Description { get; set; }

    [Mapping(ColumnName = "PortalID")]
    public int PortalID { get; set; }

    [Mapping(ColumnName = "Smith_ProductID")]
    public int Smith_ProductID { get; set; }

    [Mapping(ColumnName = "IsDigital")]
    public int IsDigital { get; set; }

    [Mapping(ColumnName = "PublisherID")]
    public long PublisherID { get; set; }

    [Mapping(ColumnName = "Released")]
    public DateTime Released { get; set; }

    [Mapping(ColumnName = "Length")]
    public long Length { get; set; }

    [Mapping(ColumnName = "CreatedOn")]
    public DateTime CreatedOn { get; set; }

    [Mapping(ColumnName = "CreatedBy")]
    public int CreatedBy { get; set; }

    [Mapping(ColumnName = "ModifiedOn")]
    public DateTime ModifiedOn { get; set; }

    [Mapping(ColumnName = "ModifiedBy")]
    public int ModifiedBy { get; set; }

    [Mapping(ColumnName = "Url")]
    [StringLength(283)]
    public string Url { get; set; }

    [Mapping(ColumnName = "dnnFileID")]
    public int dnnFileID { get; set; }

    [Mapping(ColumnName = "dnnFolderID")]
    public int dnnFolderID { get; set; }

    [Mapping(ColumnName = "TypeTagID")]
    public Guid TypeTagID { get; set; }
}

public partial class IMS_Table : IMS_Product { }

public partial class IMS_ProductController
{

    public IEnumerable<IMS_Table> _recordset {get; set;}
    string _tablename = "IMS_Product";
    string _keyname = "ProductID";

    T MapToClass<T>(SqlDataReader reader) where T : class
    {
        T returnedObject = Activator.CreateInstance<T>();
        List<PropertyInfo> modelProperties = returnedObject.GetType().GetProperties().OrderBy(p => p.MetadataToken).ToList();
        for (int i = 0; i < modelProperties.Count; i++)
            try
            {
                modelProperties[i].SetValue(returnedObject, Convert.ChangeType(reader.GetValue(i), modelProperties[i].PropertyType), null);
            }
            catch { }
        return returnedObject;
    }

    public void gets(string keyval)
    {
        string sql = string.Format("SELECT * from {0} where {1}='{2}'", _tablename, _keyname, keyval);
        getIt(sql);
     }

    public string gets(string keyval, string where)
    {
        string sql = string.Format("SELECT * from {0} where {1}='{2}' {3}", _tablename, _keyname, keyval, where);
        try
        {
            getIt(sql);
            return "Sucess: " + sql;
        }
        catch
        {
            return "Error: " + sql;
        }

    }

    public void sets(string keyval,string field, string value)
    {
        setIt(keyval, field, value);
    }

    private void getIt(string strSQL)
    {
        var table = new List<IMS_Table>();
        using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["IMS"].ConnectionString))
        {
            con.Open();
            using (var cmd = new SqlCommand(strSQL, con))
            {

                IMS_Table t = new IMS_Table();
                using (SqlDataReader reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        t = MapToClass<IMS_Table>(reader);
                        table.Add(t);
                    }
                    _recordset = table;
                    reader.Close();
                    reader.Dispose();
                }
                cmd.Dispose();
            }
            con.Close();
            con.Dispose();
        }
    }

    private void setIt(string keyval, string field, string value)
    {
        var products = new List<IMS_Table>();
        var strSQL = string.Format("update {0} set {1} = '{2}' where {3}='{4}'", _tablename, field, value, _keyname, keyval);
        using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["IMS"].ConnectionString))
        {
            con.Open();
            SqlCommand cmd = new SqlCommand(strSQL, con);
            cmd.ExecuteNonQuery();
            cmd.Dispose();
            con.Close();
            con.Dispose();
        }
    }
}
}
  1. Check @Henk Holterman's comments
  2. Change your class to public partial class IMS_ProductController<T> where T :new()

  3. Change MapToClass to T MapToClass(IDataRecord record) . Note that DataReader implements IDataRecord .

  4. Replace IMS_Table with T everywhere

Final Answer:

namespace IMS.Model
 {
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.Reflection;
using System.Linq;

[AttributeUsage(AttributeTargets.Property, Inherited = true)]
[Serializable]
public class MappingAttribute : Attribute
{
    public string ColumnName = null;
}

public partial class IMS_Controller<IMS_WorkingTable> where IMS_WorkingTable : new()
{
    private readonly string tablename;
    private readonly string keyname;

    protected IMS_Controller(string tablename, string keyname)
    {
        this.tablename = tablename;
        this.keyname = keyname;
    }

    public string _tablename { get { return tablename; } }
    public string _keyname { get { return keyname; } }
    public IEnumerable<IMS_WorkingTable> _recordset;

    IMS_WorkingTable MapToClass(IDataRecord record)
    {
        IMS_WorkingTable returnedObject = Activator.CreateInstance<IMS_WorkingTable>();
        List<PropertyInfo> modelProperties = returnedObject.GetType().GetProperties().OrderBy(p => p.MetadataToken).ToList();
        for (int i = 0; i < modelProperties.Count; i++)
            try
            {
                modelProperties[i].SetValue(returnedObject, Convert.ChangeType(record.GetValue(i), modelProperties[i].PropertyType), null);
            }
            catch { }
        return returnedObject;
    }

    public void gets(string keyval)
    {
        string sql = string.Format("SELECT * from {0} where {1}='{2}'", _tablename, _keyname, keyval);
        getIt(sql);
    }

    public string gets(string keyval, string where)
    {
        string sql = string.Format("SELECT * from {0} where {1}='{2}' {3}", _tablename, _keyname, keyval, where);
        try
        {
            getIt(sql);
            return "Sucess: " + sql;
        }
        catch
        {
            return "Error: " + sql;
        }
    }

    public void sets(string keyval, string field, string value)
    {
        setIt(keyval, field, value);
    }

    private void getIt(string strSQL)
    {
        var table = new List<IMS_WorkingTable>();
        using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["IMS"].ConnectionString))
        {
            con.Open();
            using (var cmd = new SqlCommand(strSQL, con))
            {
                IMS_WorkingTable t = new IMS_WorkingTable();
                using (SqlDataReader reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        t = MapToClass((IDataRecord)reader);
                        table.Add(t);
                    }
                    _recordset = table;
                    reader.Close();
                    reader.Dispose();
                }
                cmd.Dispose();
            }
            con.Close();
            con.Dispose();
        }
    }

    private void setIt(string keyval, string field, string value)
    {
        var products = new List<IMS_WorkingTable>();
        var strSQL = string.Format("update {0} set {1} = '{2}' where {3}='{4}'", _tablename, field, value, _keyname, keyval);
        using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["IMS"].ConnectionString))
        {
            con.Open();
            SqlCommand cmd = new SqlCommand(strSQL, con);
            cmd.ExecuteNonQuery();
            cmd.Dispose();
            con.Close();
            con.Dispose();
        }
    }
}
}


namespace IMS.Model
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;

public partial class IMM_StoreOrder
{
    [Mapping(ColumnName = "StoreOrderID")]
    [Key]
    public Guid StoreOrderID { get; set; }

    [Mapping(ColumnName = "StoreUserId")]
    public Guid StoreUserId { get; set; }

    [Mapping(ColumnName = "OrderID")]
    [Required]
    [StringLength(128)]
    public string OrderID { get; set; }

    [Mapping(ColumnName = "OrderDate")]
    public DateTime OrderDate { get; set; }

    [Mapping(ColumnName = "Status")]
    [StringLength(256)]
    public string Status { get; set; }

    [Mapping(ColumnName = "DeletedFlag")]
    public bool DeletedFlag { get; set; }

    [Mapping(ColumnName = "IPAddress")]
    [StringLength(50)]
    public string IPAddress { get; set; }
}

public partial class IMS_StoreOrderController : IMS_Controller<IMM_StoreOrder>
{
    public IMS_StoreOrderController() : base("IMM_StoreOrder", "StoreOrderID") { }

}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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