Zapnologica
Zapnologica

Reputation: 22556

How to control database parameters with Entity Framework

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:

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

Upvotes: 0

Views: 634

Answers (2)

Arturo Martinez
Arturo Martinez

Reputation: 2583

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.

Upvotes: 1

Aron
Aron

Reputation: 15772

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

Upvotes: 2

Related Questions