10

I have a model like this

public class MyModel
{
    public int MyModelId { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public string Title { get; set; }
}

I was wondering if there's a way, using Data Annotations, to set the value of a property - say Title - default to other property value, i.e. Name. Something like:

if(MyModel.Title == "") MyModel.Title = MyModel.Name;
noinstance
  • 761
  • 1
  • 7
  • 23

3 Answers3

10

If you want default value set it in entity default (parameterless) constructor. There is no need to have data annotation for something which you can do directly.

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • 1
    Default values are useful when adding a non-nullable column to an existing table with records in it. I was searching for a way to do it and came across this question - is there a way to specify the value to populate for all existing records? – Crake Aug 17 '12 at 01:16
  • 4
    @Crake this should probably be its own separate question, but I was able to do this with `defaultValueSql` in my data migration: `AddColumn("ExistingTable", "NewColumn",c => c.Int(nullable: false, defaultValueSql: "0"));` (change type and default value as necessary) – snumpy Aug 22 '12 at 17:22
4

you can tell entity framework that database will take care of that property by editing that property in SSDL of the edmx file.

Initially

<Property Name="CompanyName" Type="nvarchar" Nullable="false" MaxLength="40" />

we have change it to

<Property Name="CompanyName" Type="nvarchar" Nullable="false" MaxLength="40" StoreGeneratedPattern="Computed" />

by setting storeGeneratedPattern="Computed" we can tell to EF that the property value will be inserted by DB.

For Editing SSDL

  1. Right click the edmx file, open with XML(text) Editor.

2.Ctrl+F name of the property and just change that property

I don't know is there a way to do with data annotations.

Rajesh
  • 2,472
  • 3
  • 25
  • 31
0

It's impossible to set attribute argument as a function in general, you will get an error:

"An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type"

Grinart
  • 276
  • 2
  • 3
  • 9