Mark Williams
Mark Williams

Reputation: 612

LINQ: Property/field should inherit data on certain conditions

So I am doing a simple project management system and have run into a LINQ quandry. This is probably common. Project tasks are based on templates (which share a table with tasks in the database). A project task has several fields that are inherited by default from the task template unless they have a value. For example, a ProjectTask record with a UnitPrice of 0 will look to the ProjectTask template record to get the actual price.

How do I implement this with LINQ? I thought about doing an ObjectDataSource, but that gets away from how I am doing all the other data (in LINQ). I tried creating a derived class with code like the below, but it doesn't show up in LinqDataSource, even when I set up inheritance in the ORM designer.

I've done some googling but can't seem to find a good model. Any thoughts? Thanks as always.

public class ProjectTaskWithInheritance : ProjectTask
{
    public new decimal UnitPrice
    {
        get
        {
            if (IsServiceOverride)
                if (base.UnitPrice != 0)
                    return base.UnitPrice;

            return base.TaskTemplateRecord.UnitPrice;
        }
        set { base.UnitPrice = value; }
    }
}

Upvotes: 1

Views: 59

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726939

You are mixing up the levels of inheritance: your system models things that inherit from each other (i.e. a project task inherits a UnitPrice from a project task template); at the same time, you are trying to model it with inheritance in your .NET program. These are two different inheritances: one is in your data layer, while the other one is in your code layer.

I would suggest modeling the inheritance in the data layer with containment in the code layer, rather than using an inheritance. Each ProjectTask can have an optional instance of ProjectTask that serves as a task template; when a property is not found in the task itself, try looking it up in the template object. Make properties nullable to allow for situations when a property is not set in either the object or its template.

class ProjectTask {
    private ProjectTask Template {get;set;}
    private decimal? unitPriceOverride;
    public decimal UnitPrice {
         get {
             return unitPriceOverride ?? (Template != null ? Template.UnitPrice : null);
         }
         set {
             unitPriceOverride = value;
         }
    }
}

Upvotes: 2

Related Questions