Home > database >  Entity framework Do not include column in query result
Entity framework Do not include column in query result

Time:11-11

Using EF and .NET 6; I have this column in my model class

[Column("Central")]    
    public byte _Central { get; set; }
    [NotMapped]
    public bool Central
    {
        get
        {
            return _Central != 0;
        }
        set 
        {
            _Central = (byte) (value ? 1 : 0);
        }
    }

So when I run my code, I make a query to my database table:

var context = new GC();
        var vendors = context.Vendors
                                        .Where(s => s.No == "AC/0001")
                                        .ToList();

And finally, I convert the results to JSON

foreach (GCVendor vendor in vendors)
        {
            JsonSerializerOptions jso = new JsonSerializerOptions();
            jso.Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping;
            string jsonString = JsonSerializer.Serialize(vendor,jso);
            
        }

I only want to have the not mapped "Central" field y my jsonString , but not "_Central". Is there any way to exclude it from the query results?

CodePudding user response:

You can use [JsonIgnore] attribute.

[Column("Central")]    
[JsonIgnore]
public byte _Central { get; set; }
[NotMapped]
public bool Central
{
    get
    {
        return _Central != 0;
    }
    set 
    {
        _Central = (byte) (value ? 1 : 0);
    }
}

Note: This is part of Serialize and not EF Core.

  • Related