简体   繁体   中英

How do I access child object fields from a parent object in C#?

I am using Dapper.net as an ORM. I have an abstraact class called BusinessObject, which is inherited from by other classes that represent the tables in my database, for example SubContractorJob.

I have a method on the BusinessObject class called "Persist", which saves a record to the database:

public abstract class BusinessObject<T>
{
    public bool Persist<T>(IDbConnection db, T entity)
        where T : BusinessObject<T>, IDBObject
    {
        if (entity.Id > 0)
        {
            db.Update(entity);
            return true;
        }
        else
        {
            db.Insert(entity);
            return false;
        }
    }

}

Currently, as you can see, the Persist method takes an object as input.

Which means when I inherit from the BusinessObject class, I have to call it like this from my child object:

IDbConnection db = DBConnection.GetConnection();

    SubContractorJob s = new SubContractorJob()
            {
                Id = 3,
                SubContractorId = 6,
                JobId = 8,
                StartDate = DateTime.Today,
                EndDate = DateTime.Today.AddDays(10),
                EstimatedCost = 20000,
                ActualCost = 18000,
                IsDeleted = true
            }; 

s.Persist<SubContractorJob>(db, s);

My question is: How can I make this work without having to pass 's' when I am already calling the method in the context of s (the child object)?

I do have an interface (IDBObject) set up, so the child object is always guaranteed to have the Id field present.

I tried this:

public bool Persist<T>(IDbConnection db)
            where T : BusinessObject<T>, IDBObject
        {
            if ((typeof(T) as IDBObject).Id > 0)
            {
                db.Update(this);
                return true;
            }
            else
            {
                db.Insert(this);
                return false;
            }
        }

But got this error:

System.NullReferenceException : Object reference not set to an instance of an object.

Thanks for your help!

if ((typeof(T) as IDBObject).Id > 0)

should be changed to:

if ((this as IDBObject).Id > 0)

The primary issue with your original code is that you are trying to cast a Type (from typeof ) to IDBObject , rather than an object.

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