Jovan MSFT
Jovan MSFT

Reputation: 14650

Convert a single entity Framework object to dictionary

I have a following problem. I have a class in the entity framework model that has properties e.g.:

class Company{
    public string Name {get; set};
    public string Address {get; set};
    public string Email{get; set};
    public string WebSite {get; set};
}

I have configuration in database that defines whether or not some field should be shown or not e.g:

This is dynamic and all fields are referenced by name.

When I display object in view. It would be nice to convert somehow a single object to some dictionary where key will be property name and value will be property value so I can check for every field by name whether it should be shown or not (maybe in some for-each loop) e.g.:

CompanyDetails.cshtml

<h2>Company Details</h2>
@foreach(var property in modelDictionary.Keys){

    @if(IsVisible(property))
        @Html.Raw( modelDictionary[property] )
}

What is the best way to convert a single object from entity framework model to dictionary of properties? Should I convert it from object to dictionary in the controller action or use model metadata somehow in the view?

I can use reflection on the Company class and find all properties in the class so I can populate dictionary, but this looks like too old-school solution, so I wander is there any better way to do this?

Thanks

Upvotes: 1

Views: 1891

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039418

You could use a RouteValueDictionary which allows you to convert an object into a dictionary:

public class Company
{
    public string Name { get; set; }
    public string Address { get; set; }
    public string Email { get; set; }
    public string WebSite { get; set; }
}

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new Company
        {
            Address = "some address",
            Email = "some email",
            Name = "some name",
            WebSite = "some website"
        };
        return View(new RouteValueDictionary(model));
    }
}

and in the view:

@model RouteValueDictionary

<h2>Company Details</h2>
@foreach (var item in Model)
{
    if (IsVisible(item.Key))
    {
        <div>@item.Value</div>
    }
}

Upvotes: 3

Wouter de Kort
Wouter de Kort

Reputation: 39898

You could implement an indexer on your entity and map that trough reflection to one of the properties in your entity.

Something like:

class Entity
{
    public bool this[int index] 
    {
        get 
        {
           // Select all properties, order by name and return the property index
        }
   }

    public bool this[string name] 
    {
        get 
        {
           // Select all properties and return the correct one.
        }
   }
}

Upvotes: 1

Related Questions