简体   繁体   中英

In EF4.1 code first, What is the difference between configuring entities using annotations, configuration files, or in the OnModelCreating?

Currently I am using separate configuration files and calling them like:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Configurations.Add(new ProductConfiguration());
    base.OnModelCreating(modelBuilder);
}

It seems like most of the examples online are really basic so they define their models, the DbContext and the model configurations all in a single class. Are there and performance issues or other compelling reasons to use one over the other?

I don't know what you mean exactly with "configuration files" but there are indeed basically three options to define a model:

  • Conventions: When you create your model classes you name your properties in a way that EF can detect primary keys, foreign keys, relationships and so on automatically. If you do this consequently you neither need any data annotations nor to overwrite OnModelCreating .

  • Data annotations: Useful when you cannot or don't want to follow the convention rules. An example might be that you have an existing database whose column names doesn't match the standard naming rules of EF, for instance if you have a key column with a name which EF wouldn't recognize as a key:

     public class User { [Key] public int User_Code { get; set; } } 
  • Fluent API in OnModelCreating : For advanced mapping scenarios which you can't define with data annotations. Examples are here .

For the performance I believe it doesn't matter what you use. The approach is a question of taste and of the complexity of your model. EF creates an internal model represention only once during the lifetime of an application instance. (You can see this by setting a breakpoint in OnModelCreating : You'll reach this breakpoint only once, no matter how often you create a new DbContext .)

No, it's only a matter of readability. As your model grows you will probably get a very large configuration in OnModelCreating. As to make this more readable you break it up into separate configurations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM