I am new with Entity Framework 5. Our team is using Code First
workflow.
Before I'll start with my main question, let me first show you what I have tried (the ultimate comment of all time :D
).
public class MyDBContext : CDBContext
{
public MyDBContext() : base(connString) { }
public MyDBContext(string connStr) : base(connStr) { }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// removes some conventions
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
// ........
// model configurations which contains mappings
modelBuilder.Configurations.Add(new AccountConfiguration());
// ........
// calls base OnModelCreating
base.OnModelCreating(modelBuilder);
}
// list of all Entity
public DbSet<Account> Account { get; set; }
}
MyDBContext
is the class I have created that inherits from CBDContext
that contains override methods and which also inherits from DBContext
. One of the problems I have encountered is that entity framework doesn't handle field uniqueness. I have already read the article on Configuring/Mapping Properties and Types with the Fluent API on their site and I can't find any configuration to set a property into unique.
So what I did in order to set the field unique is to manually run several ALTER sql statements during creation,
using (MyDBContext _context = new MyDBContext(connString))
{
if (_context.Database.CreateIfNotExists())
{
_context.Database.ExecuteSqlCommand("ALTER TABLE Account ADD CONSTRAINT UQ_Account_AccountNumber UNIQUE(AccountNumber)");
_context.Database.ExecuteSqlCommand("ALTER TABLE Account ADD CONSTRAINT UQ_Account_GUID UNIQUE(GUID)");
// .... more on this in the following lines ...
}
}
My Questions:
- Am I right that entity framework don't have any configuration or data annotations to set the field unique?
- Is there a way to detect or know during runtime if EF creates a database or not so I can move or hide this statement
if (_context.Database.CreateIfNotExists())
somewhere to an available method that can be overriden?
What I really want is to remove if (_context.Database.CreateIfNotExists())
from the using statemnt and put it somewhere else or inside MyDBContext
so my code will look like this,
using (MyDBContext _context = new MyDBContext(connString))
{
Account _acc = new Account()
// ...Account properties ...
_context.Account.Add(_acc);
_context.SaveChanges();
}
Thanks.