简体   繁体   中英

Can I use EF class with navigational property as a datasource for my control?

I have a Kendo DrowpDownList that I used the EF class as it's data source.

@(Html.Kendo().DropDownList()
                    .Name("myCars")
                    .OptionLabel("--- Select Cars ---")
                    .DataValueField("ID")
                    .DataTextField("DESCRIPTION")
                    .HtmlAttributes(new { style = "width: 500px" })
                    .DataSource(s =>
                    {
                        s.Read(r =>
                        {
                            r.Action("GetAllCars", "Home");
                        });
                    })
                )

This worked fine when the table MY_CARS was the only table.

public static List<MY_CARS> GetAllCars()
{
    using (var context = new Entities())
    {
        return context.MY_CARS.ToList();
    }
}

As soon as I changed my model the same code no longer works.

I changed the model to:

MY_CARS:

ID  NAME  DESCRIPTION



MY_USER

ID NAME EMAIL



MY_USER_CARS

ID  USER_ID  CAR_ID

*USER_ID has a FK to MY_USER.ID

*CAR_ID has a FK to MY_CARS.ID

I believe the navigational properties are causing me an issue now.

Is there a way to still bind to the same class suppressing the navigational property or do I have to map my MY_CARS class into another class?

That's not likely that such way to be used as this is more about SmartUI antipattern and an another object, a view model would be better to get this done. The mapping of fields is usually done using such a tool as Automapper.

Probably the following would help, the applying of AsNoTracking() :

public static List<MY_CARS> GetAllCars()
{
    using (var context = new Entities())
    {
        return context.MY_CARS.AsNoTracking().ToList();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM