Reputation: 115
I am using Entity Framework Code First method to create my database table. The following code creates a DATETIME column in the database, but I want to create a DATE column.
//[Column(TypeName = "Date")]
public DateTime endDate { get; set; }
public DateTime startDate { get; set; }
The Column Attribute is not working.How can I create a column of type DATE, during table creation?
Thanks!
Upvotes: 0
Views: 2189
Reputation: 62213
You can map your entities to your tables in the DbContext in the OnModelCreating method. Personally I prefer to create a mapping class per entity and reference it within this method. Example:
EDIT - Updated Code. This is fully functional code.
public sealed class MyDb : DbContext
{
static MyDb()
{
System.Data.Entity.Database.SetInitializer<MyDb>(new DropCreateDatabaseAlways<MyDb>());
}
public MyDb(string nameOrConnectionString) : base(nameOrConnectionString)
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new MyMapper());
base.OnModelCreating(modelBuilder);
}
public DbSet<TesTme> Items { get; set; }
}
public sealed class MyMapper : EntityTypeConfiguration<TesTme>
{
public MyMapper()
{
// other mapping info
this.ToTable("TestTable");
HasKey(x => x.MyId);
this.Property(x => x.MyId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(x => x.dt).HasColumnType("date");
}
}
public sealed class TesTme
{
public int MyId { get; set; }
public DateTime dt { get; set; }
}
public sealed class SomeCallerOfTheDbContext
{
public void TestMe()
{
// this is the entry point
using (var context = new MyDb("connectionStringName"))
{
var items = context.Items.ToList();
}
}
}
Upvotes: 1