I am migrating to SQL Server from MySql and re-writing a website in C# (I was/am a vb.net guy) using code-first.
I wrote the following class
namespace DomainClasses.GeographyDb
{
public class PostalCode
{
[Key]
public int PostalCodeId { get; set; }
[Required]
[DataType(DataType.PostalCode)]
public string PostCode { get; set; }
[Required, ForeignKey("City")]
public int CityId { get; set; }
[Required, ForeignKey("TimeZone")]
public int TimeZoneId { get; set; }
[Required, MaxLength(30)]
public string AreaRegionPhonePrefixCode { get; set; }
[MaxLength(10)]
public string TaxRegionCode { get; set; }
public virtual City City { get; set; }
public virtual TimeZone TimeZone { get; set; }
}
I wanted to see what Entity Framework would write if it were creating the class so I created a test project and using code first from database option I imported an existing database of exact same fields as I wrote the custom classes for.
Here is what it produced;
namespace CodeFirstCreationTest
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
public partial class postalcode
{
public long PostalCodeId { get; set; }
[Required]
[StringLength(10)]
public string PostCode { get; set; }
public long CityId { get; set; }
public long TimeZoneId { get; set; }
[Required]
[StringLength(10)]
public string AreaRegionPhonePrefixCode { get; set; }
[StringLength(10)]
public string TaxRegionCode { get; set; }
public virtual city city { get; set; }
public virtual timezone timezone { get; set; }
}
}
I have a number of questions as to the differences;
Why did Entity Framework put all the
using
statements INSIDE the namespace declaration? I thought they were always to be outside and before the codeStringLength
is a data validation annotation. Why did Entity Framework put that attribute on the property, isn't it for UI validation? And now that I think of it I always putRequired
attribute on classes, is that a data validation annotation as well and not a database annotation?It created a database class using fluent API and
modelbuilder
. Is it better to annotate the class properties or do it using themodelBuilder
in theOnModelCreating
method?Why did Entity Framework make this class partial and apparently all the classes it generates as partial?