c# auto generated partial class redefine property get set

2.7k views Asked by At

I'm moving from mainly classic asp to .NET. So this may be a stupid question, but I can't find an answer.

I have an MVC App using Database First and Entity Framework. Now I would like to add some logic to the auto generated 'partial' classes. From what I have read it should be a matter of creating a new partial class with the same namespace and name. But when I do that I get an error "(This member is defined more than once)" and "Ambiguity between [partial class] and [partial class]". I understand what the error is saying, but I'm not sure how to resolve the problem.

I would like to add some logic to the set; accessor.

So in the generated class I have

public partial class QualityChecks
{
.....
    public int DailyCount { get; set; }
...
}

in my new partial class I would like to add to the set code to make sure only values greater then 0 are added. If a negative value is added it needs to be logged and changed to 0 e.g. my new partial class is:

public partial class QualityChecks    {
public int DailyCount         {        
set
        {
            DailyCount = value;
            if it's < 0 log and set to 0
        }

    }

If that's not clear maybe this will help: Currently I have loads of code that simply does

QualityChecks qc = new QualityChecks();
qc.DailyCount = enteredAmount;
....
db.QualityChecks.add(qc);

Rather then update that logic everywhere it would be nice to have it wrapped up in the QualityChecks class.

Is this the right way of going about it? If so what do I need to change to make this work?

Thank you in advance for any tips and help!

1

There are 1 answers

4
Juan On BEST ANSWER

You cannot define the same members in two different files.

You can try to define a new wrapper property (eg. MyDailyCount) that add that extra logic and update the underlying DailyCount at the end so it get persisted to database.

public int MyDailyCount 
{
   get { return DailyCount; }
   set 
   { 
         DailyCount = value; 
         // your extra logic 
    }
}