Entity Framework 6.0 Tutorials(8):Custom Code-First Conventions

Custom Code-First Conventions:

Code-First has a set of default behaviors for the models that are referred to as conventions. EF 6 provides the ability to define your own custom conventions which will be the default behavior for your models.

There are two main types of Conventions, Configuration Conventions and Model Conventions.

Configuration Conventions:

Configuration Conventions are a way to configure entities without overriding the default behavior provided in the Fluent API. You can define a configuration convention inside your OnModelCreating event or in a custom Convention Class, similar to how you would define normal entity mappings with the Fluent API.

For example, you can define a primary key of an entity that has property named {entity name} _ID, e.g. Student_ID property of Student entity will be primary key:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder
        .Properties()
        .Where(p => p.Name == p.DeclaringType.Name + "_ID")
        .Configure(p => p.IsKey());

    base.OnModelCreating(modelBuilder);
}

 

The following example shows how to set the string length of the Description property in all entities:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
        modelBuilder
            .Properties()
            .Where(p => p.Name == "Description")
            .Configure(p => p.HasMaxLength(200));

    base.OnModelCreating(modelBuilder);
}

 

You can also define custom class for this convention by deriving the Convention class as shown below:

public class PKConvention : Convention
{
    public PKConvention()
    {
        .Properties()
        .Where(p => p.Name == p.DeclaringType.Name + "_ID")
        .Configure(p => p.IsKey());

    }
}

 

Configure custom convention as shown below:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Conventions.Add<PKConvention>();
}

 

Model Conventions:

Model Conventions are based on the underlying model metadata. There are conventions for both CSDL and SSDL. Create a class that implements IConceptualModelConvention from CSDL conventions and implement IStoreModelConvention for SSDL convention.

Visit codeplex documentation for more information.

Download code-first sample project for custom conventions demo.

转载于:https://www.cnblogs.com/purplefox2008/p/5649564.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值