DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • From Naked Objects to Naked Functions
  • Working With Transactions in Entity Framework Core and Entity Developer
  • Working With Lazy Loading and Eager Loading in Entity Framework Core and Entity Developer
  • Strategies for Improving the Performance of Applications Using EF Core

Trending

  • Automatic Code Transformation With OpenRewrite
  • Start Coding With Google Cloud Workstations
  • Is Agile Right for Every Project? When To Use It and When To Avoid It
  • Event-Driven Architectures: Designing Scalable and Resilient Cloud Solutions
  1. DZone
  2. Coding
  3. Frameworks
  4. Entity Framework Core Supports Constructors With Arguments

Entity Framework Core Supports Constructors With Arguments

In this post, we show you how to use Entity Framework Core and entity constructors with arguments.

By 
Gunnar Peipman user avatar
Gunnar Peipman
·
Jun. 03, 19 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
12.7K Views

Join the DZone community and get the full member experience.

Join For Free

Keeping objects complete and valid all the time is a strategy used in different methodologies. It's perhaps most popular in Domain Driven Design (DDD). Entity Framework Core 2.1 took a big step forward on supporting entities that don't have default empty constructors. This blog post shows how to use Entity Framework Core and entity constructors with arguments.

Using Constructors With Arguments

Let's take simple Product entity that uses constructor arguments. I'll keep it minimal for demo purposes.

public class Product : BaseEntity
{

    public int Id { get; set; }
    public int TenantId { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public ProductCategory Category { get; internal set; }

    public Product(int id, int tenantId, string name, string description, ProductCategory category)
    {
        Id = id;
        TenantId = tenantId;
        Name = name;
        Description = description;
        Category = category;
    }
}

The code here builds with no errors. but problems begin when we try to query data from the database. This line of code asks DbContext for product with id 1.

var product = _context.Products.FirstOrDefault(p => p.Id == 1);  

And here's the result.

Image title

Navigational properties are currently not supported as constructor arguments by Entity Framework Core.

We can play it around by introducing two constructors. The private one is for Entity Framework Core and the public one is for developers who create new instances of a product.

public class Product : BaseEntity
{

    public int Id { get; set; }
    public int TenantId { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public ProductCategory Category { get; internal set; }

    private Product(int id, int tenantId, string name, string description)
    {
        Id = id;
        TenantId = tenantId;
        Name = name;
        Description = description;
    }

    public Product(int id, int tenantId, string name, string description, 
            ProductCategory category) : this(id, tenantId, name, description)
    {
            Category = category;
    }
}

Notice how I made Entity Framework Core constructor private. This way there's no danger of developers who are writing domain entities using this constructor and forgetting to assign it a product category.

Wrapping Up

By supporting contructors with arguments, Entity Framework Core makes it easier to write code where entities are always valid. Although navigational properties are not supported in constructor argument lists yet, we were able to work around this by making a special constructor for Entity Framework Core and leaving the classic one for developers who are working on internals of entities.

Entity Framework Database Framework

Published at DZone with permission of Gunnar Peipman, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • From Naked Objects to Naked Functions
  • Working With Transactions in Entity Framework Core and Entity Developer
  • Working With Lazy Loading and Eager Loading in Entity Framework Core and Entity Developer
  • Strategies for Improving the Performance of Applications Using EF Core

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: