Functional grouping in DbContext for EF6 using FluentAPI and Code First

J.D. Ray

I have a complex object model that I'm trying to tightly control using FluentAPI. I'm ending up with large blocks of code that look like this:

        modelBuilder.Entity<Product>().Property(t => t.Category).IsRequired();
        modelBuilder.Entity<Product>().Property(t => t.Description).IsOptional();
        modelBuilder.Entity<Product>().Property(t => t.Name).IsRequired();
        modelBuilder.Entity<Product>().Property(t => t.PricingAnalyst).IsOptional();
        modelBuilder.Entity<Product>().Property(t => t.ProductCode).IsRequired();
        modelBuilder.Entity<Product>().Property(t => t.ReplacedByProductCode).IsOptional();
        modelBuilder.Entity<Product>().Property(t => t.Section).IsOptional();
        modelBuilder.Entity<Product>().HasMany<ProductReference>(s => s.References);
        modelBuilder.Entity<Product>().HasMany<ProductWeight>(s => s.Weights);
        modelBuilder.Entity<Product>().HasMany<ProductDate>(s => s.Dates);
        modelBuilder.Entity<Product>().HasMany<ProductNote>(s => s.Notes);
        modelBuilder.Entity<Product>().HasMany<Rule>(s => s.Rules);
        modelBuilder.Entity<Product>().HasOptional<PriceDetail>(s => s.Pricing);
        modelBuilder.Entity<Product>().HasOptional<ProductCosting>(s => s.Costing);
        modelBuilder.Entity<Product>().HasMany<Update>(u => u.Updates);

It seemed to me like I could stop typing modelBuilder.Entity<Product>() so much if I could do something to the effect of

using (modelBuilder.Entity<Product>() p)
{
    p.Property(t => t.PricingAnalyst).IsOptional();
    ...
    p.HasMany<ProductReference>(s => s.References);
}

would save me a lot of effort, but I can't work out how to structure the using statement correctly. Is this the right road? If not, what do I do to shorthand the code and make it more readable?

Update:

Based on the provided answer, I've created blocks in my :DbContext file that look similar to this:

        {
            var rule = modelBuilder.Entity<Rule>();
            rule.HasKey(r => r.ID);
            rule.Property(r => r.Country).IsRequired();
            rule.Property(r => r.Description).IsOptional();
            rule.Property(r => r.ReviewDate).IsOptional();
            rule.Property(r => r.RuleNumber).IsRequired();
            rule.HasMany<Update>(r => r.Updates);
            rule.HasMany<Condition>(r => r.Conditions);
        }

I chose to wrap each block in curly braces to contain the scope of the var so I didn't have some copy/paste accident elsewhere in the code. I like the way this works, and it makes my code readable (at least to me, hopefully by others).

Justin Morgan

Sounds like you just want:

using (var p = modelBuilder.Entity<Product>())
{
    //...
}

However, this will only work if the result of modelBuilder.Entity<Product>() implements IDisposable. Going through the MSDN info on the subject, it looks like it doesn't. If not, you can probably do fine with:

var p = modelBuilder.Entity<Product>();
//...

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

Set EF6 Code First strings fluently to nvarchar(max)

分類Dev

Creating a many-to-many relationship in EF6 code first

分類Dev

FluentAPIとCodeFirstを使用したEF6のDbContextでの機能グループ化

分類Dev

Using Effort with EF6 in a DB First approach

分類Dev

EF6 Code First and mapping via annotations, how do I build the configuration?

分類Dev

EF6 Code First Migration com um único banco de dados de contexto múltiplo

分類Dev

EF6 code first multiple 1-to-many mapping issue / "Multiplicity" error

分類Dev

EF6 Code First in WPF create local DB in application folder

分類Dev

DbContext / EF6でのeSQLクエリ

分類Dev

"the provider did not return a providermanifesttoken" using Oracle MangedDataAccess with EF 6 Code First

分類Dev

Entity Framework Code First FluentAPIを使用してテーブル名を指定する方法

分類Dev

1対1の識別関係のためのEntityFramework Code First FluentAPI構成

分類Dev

私のSeed()メソッドがCode First EF6で呼び出されることはありません

分類Dev

MVC 5 - How to update relational table using EF code first

分類Dev

EF6FluentAPIに列名規則を追加

分類Dev

How to query from the table using group by with EF6?

分類Dev

Connecting 2 tables to a third using C# EF6

分類Dev

EF6 Database First - EF trying to create my database (but all tables already exist)

分類Dev

EF6のDBContextのモックが期待どおりに機能しない

分類Dev

EF 6 FluentAPIのCRUDから読み取ったマップ

分類Dev

FluentAPIを使用したEF外部キー

分類Dev

EF6 mapping many-to-many using same column name

分類Dev

How to create the sequence and apply two tables in SQL Server using Entity framework 6 code first approach?

分類Dev

EF Code first 1 to 1 relationship error

分類Dev

EF Code First Navigation Property to same table

分類Dev

EF Code First Foreign Key Same Table

分類Dev

EF reverse engineering code first and stored procedures

分類Dev

Custom value type, EF Code First and routing

分類Dev

How can I use SQL Server JSON_VALUE function in EF 6 Code First for classic .NET

Related 関連記事

  1. 1

    Set EF6 Code First strings fluently to nvarchar(max)

  2. 2

    Creating a many-to-many relationship in EF6 code first

  3. 3

    FluentAPIとCodeFirstを使用したEF6のDbContextでの機能グループ化

  4. 4

    Using Effort with EF6 in a DB First approach

  5. 5

    EF6 Code First and mapping via annotations, how do I build the configuration?

  6. 6

    EF6 Code First Migration com um único banco de dados de contexto múltiplo

  7. 7

    EF6 code first multiple 1-to-many mapping issue / "Multiplicity" error

  8. 8

    EF6 Code First in WPF create local DB in application folder

  9. 9

    DbContext / EF6でのeSQLクエリ

  10. 10

    "the provider did not return a providermanifesttoken" using Oracle MangedDataAccess with EF 6 Code First

  11. 11

    Entity Framework Code First FluentAPIを使用してテーブル名を指定する方法

  12. 12

    1対1の識別関係のためのEntityFramework Code First FluentAPI構成

  13. 13

    私のSeed()メソッドがCode First EF6で呼び出されることはありません

  14. 14

    MVC 5 - How to update relational table using EF code first

  15. 15

    EF6FluentAPIに列名規則を追加

  16. 16

    How to query from the table using group by with EF6?

  17. 17

    Connecting 2 tables to a third using C# EF6

  18. 18

    EF6 Database First - EF trying to create my database (but all tables already exist)

  19. 19

    EF6のDBContextのモックが期待どおりに機能しない

  20. 20

    EF 6 FluentAPIのCRUDから読み取ったマップ

  21. 21

    FluentAPIを使用したEF外部キー

  22. 22

    EF6 mapping many-to-many using same column name

  23. 23

    How to create the sequence and apply two tables in SQL Server using Entity framework 6 code first approach?

  24. 24

    EF Code first 1 to 1 relationship error

  25. 25

    EF Code First Navigation Property to same table

  26. 26

    EF Code First Foreign Key Same Table

  27. 27

    EF reverse engineering code first and stored procedures

  28. 28

    Custom value type, EF Code First and routing

  29. 29

    How can I use SQL Server JSON_VALUE function in EF 6 Code First for classic .NET

ホットタグ

アーカイブ