Notmapped property and OData 4 endpoint can't get the property to show on front end

Viewed 394

I am using Entity Framework Core 5 with OData 4 endpoints in my project. I am having an issue with a [NotMapped] property not showing up to be used in my front end. I have read that OData ignores not mapped properties but I have not found a solution on how to get OData to not ignore the property so that I can use it in my front end without adding it to my database.

What I am trying to accomplish is to include the count of each category assigned in the asset table.

Here is what I have for my DTO

public class CategoryDto : DropDownDto
{
    /*
     * String property that gets/sets the category name
     */
    public string CategoryName { get; set; }
    [NotMapped]
    public int Count { get; set; }
}

and in my CategoriesController I have this

public async Task<ActionResult<IQueryable<CategoryDto>>> GetCategories()
{
    var categories = await _context.Categories
            .Include(a => a.Assets)
            .Select(l => new CategoryDto()
            {
                Id = l.Id,
                CategoryName = l.CategoryName,
                Count = l.Assets.Count
            })
            .ToListAsync();
    var categoryDto = _mapper.Map<List<Category>>(categories);

    return Ok(categoryDto);
}

When I run my app and put a breakpoint on the return and view the data I can see that count is working as expected. It has the proper count of assets assigned to a category which is what I want

enter image description here

But when I run postman to see the values all I get is this

"value": [
        {
            "id": 1,
            "categoryName": "Computers"
        },
        {
            "id": 2,
            "categoryName": "Tools"
        }
    ]

So the issue is how to I get the OData endpoint to included the notmapped property?

Any insight would be great, if more info is needed please ask and Ill get it for you

1 Answers

In the OData GetEdmModel method, use the following commands to add the [NotMapped] property to the IEdmModel object.

    IEdmModel GetEdmModel()
    { 
        var odataBuilder = new ODataConventionModelBuilder();
        odataBuilder.EntitySet<Student>("Students");
                    
        odataBuilder.EntityType<Student>().Property(c => c.Score);
        //or using the HasKey method.
        //odataBuilder.EntityType<Student>().HasKey(x => x.Score);

        return odataBuilder.GetEdmModel();
    }

the Student model like this:

public class Student
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    [NotMapped]
    public int Score { get; set; }
}

Before adding the [NotMapped] property to the IEdmModel object. The result like this:

enter image description here

After adding the [NotMapped] property to the IEdmModel object. the result as below:

enter image description here

Related