0

I am using EF with an asp.net mvc project which I am using c# for.

I am busy designing the data model now and I would like to know if there is a way to control certain properties about each property not only in the model object but also in the persisted storage (MS SQL in my case).

Here is an example of my current domain model.

public class Network
{
    [Required]
    public int networkID { get; set; }

    [Required]
    [StringLength(30, MinimumLength = 3)]
    [DisplayName("Name")]
    public string name { get; set; }

    [Required]
    [Range(0, 7)]
    [DisplayName("Start Code")]
    public int startCode { get; set; }

    [Required]
    [DisplayName("Frequency (Mhz)")]
    public decimal frequency { get; set; }
    //public virtual List<Block> blocks { get; set; }

    //The number of used up blocks. Will increase by the block size of every newly created block.
    [Required]
    [Range(0, 65535)]
    public int blockCounter { get; set; }

    //Number of blocks within the network.
    [Range(0,65535)]
    public int noOfBlocks { get; set; }
}

Now the questions relating to this:

This line:

[Range(0,65535)]
public int noOfBlocks { get; set; }  

Will This actully limit the int in the database to that size? Or is this purely for validation purposes?

If not how can I define certain properties about a specific attribute such as:

  • If it is a primary key?
  • Set a default value.
  • Specify a length or range of a field.
  • define if it can be null.

Basically the functionality which MS SQL offerers when creating a entry.

Zapnologica
  • 22,170
  • 44
  • 158
  • 253

2 Answers2

2

There are a few ways to influence the StorageModel of EF-CodeFirst. The two ways I can think of off the top of my head are by Attribute and by Fluent-Registration.

Data Annotation Attributes

Fluent Mapping

Aron
  • 15,464
  • 3
  • 31
  • 64
1

The RangeAttribute does not control the value range in the database. It creates the column as an int column accepting all the integers that the int type can accepts. If you create a store procedure that sets the value of this column it will not be validated against this range. It would be nice if entity framework creates a constraint on the column, but this doesn't happen.

The RangeAttribute validates your data right before it persists your entities in the data store.

Arturo Martinez
  • 3,737
  • 1
  • 22
  • 35
  • Thanks that explains that section of my questions nicely. Ok but now if i use Data Annotations like so: `[MaxLength(10),MinLength(5)] public string BloggerName { get; set; }` will that then do both validation and persistence validation? – Zapnologica Jan 22 '14 at 14:05
  • Again, this would only validate your data right before you insert or update the entity. In the case of ASP.NET scaffolding the data would be validated at the page level by using the same data annotations. – Arturo Martinez Feb 04 '14 at 04:19