实体框架代码优先模型构建器

时间:2019-12-17 20:46:18

标签: c# entity-framework entity-framework-6 ef-code-first ef-fluent-api

在我的DbContext课堂上,我有以下内容:

void OnModelCreating(DbModelBuilder modelBuilder)
{
   modelBuilder.Properties<string>().Configure(c => { c.HasMaxLength(250); });
}

但是在EntityTypeConfiguration类中,对于我拥有的特定模型也是如此:

{
   Property(p => p.Name).HasMaxLength(500);
}

问题在于,在Configuration类中将属性设置为500无效,并且EF仍在验证最大值为250。

我如何将常规设置设置为250,但需要在每个班级中使用流利的api进行覆盖?

3 个答案:

答案 0 :(得分:3)

如果您要为字符串字段提供500个字符。

您可以使用“ MaxLength ”属性来做到这一点。


我正在创建一个如下的示例表。

我的上下文配置。

void OnModelCreating(DbModelBuilder modelBuilder)
{
   modelBuilder.Properties<string>().Configure(c => { c.HasMaxLength(250); });
}

我正在创建一个名为FooEntity的表。

using System;
using System.ComponentModel.DataAnnotations;

namespace Foo.Model
{
    public class FooEntity
    {
        [MaxLength(500)]
        public string FooName { get; set; }
    }
}

添加此属性后,迁移输出如下。 即使给出了250个字符的限制,它在SQL中也将作为500个字符传递。

CreateTable(
    "dbo.FooEntity",
    c => new
        {
            FooName = c.String(maxLength: 500)
        });

答案 1 :(得分:1)

First, create an empty interface.

public interface IEntityMap
{ 

}

为每个实体创建一个用于流畅配置的类:

public class BlogMap : IEntityMap
{
   public BlogMap(ModelBuilder builder)
   {
    builder.Entity<blog>(b =>
     {
        b.HasKey(e => e.Id);
        b.Property(e => e.Url).HasMaxLength(500).IsRequired();
    });
  }
}


public class PostMap : IEntityMap

{
public PostMap(ModelBuilder builder)
 {
    builder.Entity<post>(b =>
    {
        b.HasKey(e => e.Id);
        b.Property(e => e.Title).HasMaxLength(128).IsRequired();
        b.Property(e => e.Content).IsRequired();
    });
 }
}

然后,通过反射加载映射类:

private void RegisterMaps(ModelBuilder builder)
{
  // Full .NET Framework
  var maps = Assembly.GetExecutingAssembly().GetTypes()
    .Where(type => !string.IsNullOrWhiteSpace(type.Namespace) 
        && typeof(IEntityMap).IsAssignableFrom(type) 
        && type.IsClass).ToList();

  // .NET Core
  var maps = typeof(a type in that   
         assembly).GetTypeInfo().Assembly.GetTypes()
        .Where(type => !string.IsNullOrWhiteSpace(type.Namespace) 
        && typeof(IEntityMap).IsAssignableFrom(type) 
        && type.IsClass).ToList();

  foreach (var item in maps)
    Activator.CreateInstance(item, BindingFlags.Public | 
    BindingFlags.Instance, null, new object[] { builder }, null);
  }

在OnModelCreating方法内,调用RegisterMaps:

 protected override void OnModelCreating(ModelBuilder builder)
 {
    RegisterMaps(builder);

    base.OnModelCreating(builder);
 }

有关更多详细信息。 请参阅此链接。.我希望这可以解决您的问题

https://www.codeproject.com/Tips/1119108/Organizing-Fluent-Configurations- 成独立的Cla

答案 2 :(得分:-1)

@Lutti Coelho:我的错

在下面的OnModelCreating方法中添加代码

modelBuilder.Entity<Student>()
                    .Property(p => p.StudentName)
                    .HasMaxLength(50);
相关问题