0

This is beginning of my auto generated class Customer:

namespace Winpro
{
using System;
using System.Collections.Generic;

public partial class Customer
{
    public Customer()
    {
        this.Blocked = false;
        this.Code = "#00000";
        this.RuleId = 1;
        this.LocationId = 1;
        this.Contacts = new ObservableListSource<Contact>();
    }

    public int Id { get; set; }
    public string Name { get; set;
    public System.DateTime Added { get; set; }
    ...

Why I can't extend class in this way.

namespace Winpro
{
public partial class Customer
{
    public Customer()
    {
        this.Added = DateTime.Now;
    }

Looking for simple example of setting default values in separate class or override SaveChanges() method.

Thanks

Carlo
  • 151
  • 1
  • 3
  • 16

2 Answers2

1

A partial class is a class divided in multiple files. It is still a single class, and you can't have two constructors with the same signature.

You can try:

  • Define a new constructor which takes parameter for DateTime
  • Call the default constructor with this
  • Assign the value to the Added property from the parameter


namespace Winpro
{
public partial class Customer
{
    public Customer(DateTime parameterAdded)
     : this() //call the default constructor
    {
        this.Added = parameterAdded; //DateTime.Now;
    }
Habib
  • 219,104
  • 29
  • 407
  • 436
  • I'm still getting error when I try to insert into db : `The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.` While values set up in the default constructor works well – Carlo Jan 23 '14 at 16:49
  • @Carlo, that seems like a different issue, you can see this question http://stackoverflow.com/questions/4608734/the-conversion-of-a-datetime2-data-type-to-a-datetime-data-type-resulted-in-an-o – Habib Jan 23 '14 at 16:51
  • Have read many Q&A, even ask my own like http://stackoverflow.com/questions/21295123/dbcontext-entity-framework-datetime-now-fields but I just don't get it. When I drag controls on my form and call customerBindingSource.AddNew() I want to set default values for fields. With values in default constructor everything work well but not for values defined in my second part of partial class. Maybe I don't understand how to use your example? – Carlo Jan 23 '14 at 17:01
0

Go with a partial method

In the generated class

public partial class Customer
{
    public Customer()
    {
        this.Blocked = false;
        this.Code = "#00000";
        this.RuleId = 1;
        this.LocationId = 1;
        this.Contacts = new ObservableListSource<Contact>();
        AdditionnalInitialisation();
    }

    partial void AdditionnalInitialisation();

In your extension:

public partial class Customer
{
    partial void AdditionnalInitialisation()
    {
        this.Added = DateTime.Now;
    }
}
Alexandre Rondeau
  • 2,667
  • 24
  • 31