RisingHerc
RisingHerc

Reputation: 764

EF Core - Can I make Entity Framework map only to only specific columns in the database?

I am using EF Core 2.0 in my project.

I have the table schema as somewhat like this:

Table: Report

Id int
Name varchar
Description varchar
<ExtraColumn> <sometype>

And my model class would probably be like this:

class Report
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public <sometype> <SomeProperty> { get; set; }
}

In my project, I don't want to use some columns in the table in the EF mapping. So, I would like to exclude it from the entity mapping.

Similarly, I want to use some properties in the model class for other internal purposes (not for EF mapping).

Is this possible at all?

P.S. I have heard that the Ignore() method in EF Core addresses the second requirement of mine. But, what about the first one?

Is there a way out?

Upvotes: 1

Views: 2597

Answers (1)

Sasan
Sasan

Reputation: 4220

By convention, public properties with a getter and a setter will be included in the model.

You can use Data Annotations or Fluent API to exclude a property from the model.

Data Annotation:

class Report
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }

    [NotMapped]
    public <sometype> <SomeProperty> { get; set; }
}

Fluent API:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Report>()
        .Ignore(b => b.<SomeProperty>);
}

Upvotes: 4

Related Questions