简体   繁体   English

我可以将具有导航属性的EF类用作控件的数据源吗?

[英]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. 我有一个Kendo DrowpDownList,它使用EF类作为数据源。

@(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. 当表MY_CARS是唯一的表时,此方法运行良好。

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? 有没有办法绑定到抑制导航属性的同一个类,还是必须将MY_CARS类映射到另一个类?

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. 不太可能使用这种方式,因为这更多地是关于SmartUI反模式和另一个对象,视图模型会更好地做到这一点。 The mapping of fields is usually done using such a tool as Automapper. 通常使用诸如Automapper之类的工具来完成字段的映射。

Probably the following would help, the applying of AsNoTracking() : 应用AsNoTracking()可能会有所帮助:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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