3

我正在开发 WCF Web 服务,并使用 ADO.Net Entities 访问数据库。

我使用这种方法将一些 Database 对象转换为 Contract 对象:

public static List<BlockContract> FormBlocks(int formId)
{
    List<BlockContract> blocksList = null;

    using (var vAdmEntities = new ADMDatabase.ADMEntities())
    {
        var blockEntities = from f in vAdmEntities.Form
                        where f.formId == formId
                        select f.Block;
        if (blockEntities != null)
        {
            blocksList = new List<BlockContract>(blockEntities.Count());
            foreach (ADMDatabase.Block b in blockEntities)
            {
                BlockContract blockContract = new BlockContract
                {
                    blockId = b.blockId,
                    name = b.name,
                    orderInForm = b.orderInForm
                };
                blocksList.Add(blockContract);
            }
        }
    }

    return blocksList;
}

在这里,foreach (ADMDatabase.Block b in blockEntities)我得到一个错误:

Cannot convert type 'System.Data.Objects.DataClasses.EntityCollection<ADMDatabase.Block>' to 'ADMDatabase.Block'

我该如何解决这个错误?

4

1 回答 1

2

你需要改变你的循环;

foreach (var blockItems in blockEntities){
     foreach (ADMDatabase.Block b in blockItems)
            {
                BlockContract blockContract = new BlockContract
                {
                    blockId = b.blockId,
                    name = b.name,
                    orderInForm = b.orderInForm
                };
                blocksList.Add(blockContract);
            }
}

您正在选择具有以下内容的阻止实体;

var blockEntities = from f in vAdmEntities.Form
                        where f.formId == formId
                        select f.Block;

在这里,如果您调试 blockEntities,您将类似于列表列表,因为 Form.Block 是块项目的列表。

于 2012-04-10T10:33:20.170 回答