0

I am building an ASP.NET Core Web API with EF Core 7, and am using a code-first approach. One of my classes PersonType inherits from a base class that has an Id property, but I want it to ignore the Id property. I am able to prevent the Id from appearing in the PersonType SQL Server table by including .Ignore(b => b.Id); in the Fluent Api.

However - I do not want the Id to appear in the serialized JSON Get result. Right now, the Id property does appear in the serialized result, but it

This is what my class looks like.

[PrimaryKey(nameof(PersonId), nameof(Type))]
public class PersonType : BaseObject
{
    public Guid PersonId { get; set; }
    public string Type { get; set; } = string.Empty;
}

public class PersonTypeEntityTypeConfiguration : BaseObjectTypeConfiguration<PersonType>
{
    public override void Configure(EntityTypeBuilder<PersonType> builder)
    {
        builder
            .Ignore(b => b.Id);

        base.Configure(builder);
    }
}

And this is what the current serialized result looks like.

"personTypes": [
      {
        "personId": "73380575-90ff-48ba-b95e-cafaafe79c5c",
        "type": "Artist",
        "id": "00000000-0000-0000-0000-000000000000",
        "dateUtcUpdated": "2022-12-02T19:58:24.62"
      }

As you can see, the id is getting populated with the default Guid, but I don't want it to appear at all. I don't want to add [JsonIgnore] to the base class, since that would prevent it from being serialized in all of the other classes that inherit from the base class. What can I do to solve this?

6
  • 3
    Don't use EF types as DTOs. Just don't. DTOs and entity classes represent different things which is the main reason why you shouldn't re-use types like that. What follows are dozens of practical reasons why you shouldn't: e.g. overposting attacks, stack-overflows from serialized navigation property lazy-loading, attribute use conflicts, etc. Commented Dec 2, 2022 at 20:35
  • You do Ignore for EntityFramework not for ASP.NET MVC Commented Dec 2, 2022 at 20:38
  • builder.Ignore(b => b.Id); <-- This does not do what you think it does, nor what you want it to do, and what you think you want is actually very undesirable. Commented Dec 2, 2022 at 20:40
  • @dai can you suggest a redesign? Commented Dec 2, 2022 at 20:42
  • @sion_corn Yes: simply define a separate DTO class and use AutoMapper or manual mapping. Commented Dec 2, 2022 at 20:43

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.