使用json和Entity Framework

时间:2017-02-21 13:59:30

标签: c# json ajax asp.net-mvc entity-framework

我正在尝试通过ajax调用填充下拉列表我的代码工作正常,直到我以Json格式发回结果(对象列表)。

这是我试图填写的实体模型:

 public partial class stkInvoicesTypesTbl
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public stkInvoicesTypesTbl()
    {
        this.stkInvoicesTbls = new HashSet<stkInvoicesTbl>();
    }

    public int invTypesTableId { get; set; }
    public string invTypeDesc { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<stkInvoicesTbl> stkInvoicesTbls { get; set; } //this property throw Exception and i think here is my problem
}

这是我的ajax调用和脚本代码

var InvType = []

// fetch invoice type from database
function LoadInvoiceType(element)
{   
    if (InvType.length == 0) {
        //ajax function to fetch data
        $.ajax({
            type: "GET",
            url: '/InvoiceItm/getInvoiceType',

            success: function (data) {
                InvType = data;

                renderInvoiceType(element);
            },
            error: function (data) {
                InvType = data;
            }
        })
    }
    else {
        //render invoice type to elements
        renderInvoiceType(element);
    }
}

function renderInvoiceType(element)
{
    var $ele = $(element);
    $ele.empty();

    $.each(InvType, function (i, val) {
        $ele.append($('<option/>').val(val.invTypesTableId).text(val.invTypeDesc));
    })
}

我的动作控制器:

public JsonResult getInvoiceType()
{
        List<stkInvoicesTypesTbl> InvoiceTypes = new List<stkInvoicesTypesTbl>();

        using (iraqEntities dc = new iraqEntities())
        {
            InvoiceTypes = dc.stkInvoicesTypesTbls.OrderBy(a => a.invTypeDesc).ToList();
        }

        return new JsonResult { Data = InvoiceTypes, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}

我的观点:

<td><label for="input-text" class="col-sm-1 control-label">Invoice Type</label> </td>
            <td>
                <select type="text" id="InvoiceType" class="col-sm-3 form-control" onchange="LoadInvoiceType(this)"></select>

            </td>

我的列表在控制器中正确填充但是当我以json格式发送回来时(返回JsonResult ...),它返回错误。

以下是我调试的一些屏幕截图可能会有所帮助:

return my data from database and fill my list in controller

this property is generated automatically from Entity Framework (foreign key relation) and it's throwing an exception so I think my problem lies here

所以,任何人都可以帮助我解决我的问题

1 个答案:

答案 0 :(得分:0)

您需要在查询中包含属性stkInvoicesTbls

    using (iraqEntities dc = new iraqEntities())
    {
        InvoiceTypes = dc.stkInvoicesTypesTbls
                         .Include("stkInvoicesTbls")
                         .OrderBy(a => a.invTypeDesc)
                         .ToList();
    }