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
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
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

Migrate, Modernize and Build Java Web Apps on Azure: This live workshop will cover methods to enhance Java application development workflow.

Modern Digital Website Security: Prepare to face any form of malicious web activity and enable your sites to optimally serve your customers.

E-Commerce Development Essentials: Considering starting or working on an e-commerce business? Learn how to create a backend that scales.

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

  • A Comprehensive Approach to Performance Monitoring and Observability
  • Unlocking the Power of Streaming: Effortlessly Upload Gigabytes to AWS S3 With Node.js
  • What Is SQL Vector Database?
  • How to Integrate Istio and SPIRE for Secure Workload Identity
  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.

Gunnar Peipman user avatar by
Gunnar Peipman
·
Jun. 03, 19 · Tutorial
Like (2)
Save
Tweet
Share
12.2K 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

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • 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: