通过mysql和Entity Framework中的关系访问表的问题

时间:2013-07-07 17:50:05

标签: c# mysql entity-framework

我正在使用C#和Entity Framework来访问MySQL数据库。 我正在抓取存储过程的结果,并尝试将它们转换为对象列表。但是,只要涉及通过一对多关系引用表的部分,它就会因错误而失败

There is already an open DataReader associated with this Connection which must be closed first.

我正在使用的代码在这里:

using System;
using System.Collections.Generic;
using System.Data.Objects;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CarHireCommon.DataObjects;

namespace CarHireServer
{
    public class DatabaseHandler
    {
        protected static DatabaseHandler instance;
        protected carhireEntities1 Entities;
        public static DatabaseHandler GetInstance()
        {
            if (instance == null)
                instance = new DatabaseHandler();
            return instance;
        }

    public DatabaseHandler()
    {
        Entities = new carhireEntities1();
    }



        public List<AvailableAssets> GetAvailableAssets(DateTime startDate, DateTime endDate)
        {
            ObjectResult<asset> res = Entities.GetAvailableAssets(startDate, endDate);

            List<AvailableAssets> list = new List<AvailableAssets>();
            foreach(var assetRes in res)
            {
                AvailableAssets asset=new AvailableAssets();
                asset.id = assetRes.id;
                asset.Comment = assetRes.comments;
                asset.Make = assetRes.make;
                asset.Model = assetRes.model;
                asset.Fuel = assetRes.fuel;
                asset.LongTerm = assetRes.longterm;
                // This is the line that errors:
                asset.Category = assetRes.category.categoryname;
                list.Add(asset);
            }

            return list;
        }
    }
}

我已经告诉它存储过程返回哪个表,其他变量可以正确访问。

我也尝试过这么做:

var cat = from b in Entities.categories where b.id == assetRes.category_id select b;
asset.Category = cat.FirstOrDefault<category>().categoryname;

然而,事情仍然存在完全相同的错误。

1 个答案:

答案 0 :(得分:1)