简体   繁体   中英

Referencing derived object in a base class

I have a data mapping helper class that uses generics and reflection.

Since I'm using reflection and generics in my helper class, the code for standard CRUD operations are identical across all of my business objects (as seen in the base class Create() method), so I'm trying to use a base BusinessObject class to handle the repetitive methods.

I want the base class to be able to call my generic DataUtils methods, which for example, accept a reference to the derived business object object to populate SQL parameters.

DataUtils.CreateParams expects an object of type T and a bool (indicates insert or update).

I want to pass "this," representing my derived object the base class, but I'm getting compile error "The best overloaded match contains invalid parameters."

If I implement Create() in the derived class, and pass the base class's Create method a reference to "this", it works - but then I'm still implementing all the CRUD methods, identically, in each business object class. I want the base class to handle these.

Is it possible for a base class to call a method and pass a reference to the derived object?

Here's my base class:

public abstract class BusinessObject<T> where T:new()
{
    public BusinessObject()
    { }

    public Int64 Create()
    {
        DataUtils<T> dataUtils = new DataUtils<T>();
        string insertSql = dataUtils.GenerateInsertStatement();
        using (SqlConnection conn = dataUtils.SqlConnection)
        using (SqlCommand command = new SqlCommand(insertSql, conn))
        {
            conn.Open();

            //this line is the problem
            command.Parameters.AddRange(dataUtils.CreateParams(obj, true));
            return (Int64)command.ExecuteScalar();

        }
    }
}

}

And a derived class:

 public class Activity: BusinessObject<Activity>
 {
    [DataFieldAttribute(IsIndentity=true, SqlDataType = SqlDbType.BigInt)]
    public Int64 ActivityId{ get; set; }
    ///...other mapped fields removed for  brevity

    public Activity()
    {
        ActivityId=0;
    }

    //I don't want to have to do this...
    public Int64 Create()
    {

        return base.Create(this);
    }

Just cast this to T :

dataUtils.CreateParams((T)this, true);

If you create a public class Evil : BusinessObject<Good> , that will throw an InvalidCastException.

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