繁体   English   中英

LINQ加入Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:'对象'不包含以下内容的定义:

[英]LINQ Join Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'object' does not contain a definition for

我正在使用EF6并进行一些LINQ连接,然后将新结构传递给视图。 问题在于,由于这些新加入的结构是内部的,因此它将引发Microsoft.CSharp.RuntimeBinder.RuntimeBinderException

C#

 var carMains = this.DatabaseManager.carClaims.Join(this.DatabaseManager.carConvictions, l => l.request_id, r => r.request_id, (l, r) => new { l.claim_amount, r.conviction_driver }).Take(10);
 return View("CarJoin", carMains.ToList());

视图

@model dynamic
@foreach (var m in Model)
{
    <br>
    <div>@(m.claim_amount ?? "")</div>
     <br>
    <div>@(m.conviction_driver ?? "")</div>
     <br>
}

我看到的解决方案是为每个联接创建对象并具有强类型的视图,这在我们讨论具有200多个实体的多个数据库模型时将非常耗时。

我确信到目前为止,已经有人遇到这种情况,并且可能找到了一些耗时较少的解决方案。 如何在无需显式定义结构的情况下将其传递给视图?

整理自己

枚举后,可以将其ExpandoObjectExpandoObject ,然后视图将很高兴处理动态

C#中的Expando扩展

public static class ExtensionMethods
{
    public static ExpandoObject ToExpando(this object obj)
    {
        IDictionary<string, object> expando = new ExpandoObject();
        foreach (PropertyDescriptor propertyDescriptor in TypeDescriptor.GetProperties(obj))
        {
            var value = propertyDescriptor.GetValue(obj);
            expando.Add(propertyDescriptor.Name, value == null || new[]
            {
                typeof (Enum),
                typeof (String),
                typeof (Char),
                typeof (Guid),
                typeof (Boolean),
                typeof (Byte),
                typeof (Int16),
                typeof (Int32),
                typeof (Int64),
                typeof (Single),
                typeof (Double),
                typeof (Decimal),
                typeof (SByte),
                typeof (UInt16),
                typeof (UInt32),
                typeof (UInt64),
                typeof (DateTime),
                typeof (DateTimeOffset),
                typeof (TimeSpan),
            }.Any(oo => oo.IsInstanceOfType(value))
                ? value
                : value.ToExpando());
        }

        return (ExpandoObject)expando;
    }
}

然后查询获得附加的.ToList().Select(o => o.ToExpando()); 喜欢:

var carMains =
            this.DatabaseManager.GetEntities<carClaims>()
                .Join(this.DatabaseManager.GetEntities<carConvictions>(), l => l.request_id, r => r.request_id, (l, r) => new {l.claim_amount, r.conviction_driver})
                .Take(10)
                .ToList()
                .Select(o => o.ToExpando());
        return View("CarJoin", carMains.ToList());

查看代码完全不变。

希望这可以节省您一些时间。

暂无
暂无

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

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