如何从 C# 中的父对象访问子对象字段?

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

我正在使用 Dapper.net 作为 ORM。我有一个名为 BusinessObject 的抽象 class,它是由代表我的数据库中的表的其他 class 继承而来,例如 SubContractorJob。

我在 BusinessObject class 上有一个名为 "Persist" 的方法,它将一条记录保存到数据库中:

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;
        }
    }

}

目前,如您所见,Persist 方法将对象作为输入。

这意味着当我从 BusinessObject class 继承时,我必须从我的子对象中这样调用它:

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);

我的问题是: 当我已经在 s(子对象)的上下文中调用方法时,如何才能在不必传递 's' 的情况下完成这项工作?

我确实设置了接口 (IDBObject),因此始终保证子对象具有 Id 字段。

我试过这个:

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;
            }
        }

但是出现这个错误:

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

感谢您的帮助!

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

应改为:

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

您的原始代码的主要问题是您试图将 Type(从 typeof)转换为 IDBObject,而不是对象。