c# - 如何将对象从 IEnumerable 集合添加到数据库?

标签 c# database entity-framework ienumerable

我有一个 ienumerable 实体的集合要添加到数据库中,但似乎需要进行一些转换。谁能指出我正确的方向?

bool InsertDetails(DataTable detailTable, string fileName)
{
    using (SunseapEBTContext context = new SunseapEBTContext())
    {
        if (InsertMaster(fileName))//if creating master record successful
        {                    
            int masterId = GetSPReadingM(m => m.FileName == fileName).SPReadingMasterId; //get MasterID of file uploaded

             var details = detailTable.AsEnumerable().Select(row => new LeasingSPReadingDetailEntity()//new entity from datatable
             {
                //SPReadingId = row.Field<long>("ProductID"),

                        SPReadingMasterId = masterId,
                        BillCycleYear = int.Parse(row.Field<int>("Bill Cycle").ToString().Substring(0, 4)),
                        BillCycleMonth = byte.Parse(row.Field<byte>("Bill Cycle").ToString().Substring(4))

            });
            foreach(IEnumerable<LeasingSPReadingDetailEntity> detail  in details)
            {                       
                context.LeasingSPReadingDetailEntities.AddObject(detail);
            }
            context.SaveChanges();                    
        }
        return true;
    }
}

在foreach循环中,抛出异常

CS1503 Argument 1: cannot convert from 'System.Collections.Generic.IEnumerable' to 'SunseapEBT.Domain.BillingModule.LeasingContract.Entity.LeasingSPReadingDetailEntity'

LeasingSPReadingDetailEntity 类:

public class LeasingSPReadingDetailEntity
{
    public long SPReadingId { get; set; }
    public int SPReadingMasterId { get; set; }
    public int BillCycleYear { get; set; }
    public byte BillCycleMonth { get; set; }

}

更多信息: 上传包含详细信息的文件,并将在一个表中创建主记录。文件中的详细信息将被添加到一个单独的表中,其中包含第一个表中自动生成的 masterId。问题是无法将详细信息添加到数据库中。

编辑: 我发现了为什么会出现错误。错误是因为文件的内容。有些行没有输入值,最后一行不遵循其余行的格式,因为它显示了总行数。感谢大家的帮助!

最佳答案

@slawekwin 评论就是答案。但我认为有更好的解决方案,因为您的代码似乎迭代了 2 次:第一次生成新的 Enumerable(浪费内存),第二次将对象添加到上下文。

不妨在迭代每一行时直接添加对象。

foreach(var row in detailTable.AsEnumerable())
{                       
    context.LeasingSPReadingDetailEntities.AddObject(
        new LeasingSPReadingDetailEntity()//new entity from datatable
        {
           //SPReadingId = row.Field<long>("ProductID"),

           SPReadingMasterId = masterId,
           BillCycleYear = int.Parse(row.Field<string>("Bill Cycle").Substring(0, 4)),
           BillCycleMonth = byte.Parse(row.Field<string>("Bill Cycle").Substring(4)),
           AccountNumber = row.Field<string>("Account No."),
           PeriodStart = row.Field<DateTime>("Period Start"),
           PeriodEnd = row.Field<DateTime>("Period End"),
           TownCouncil = row.Field<string>("Customer Name"),
           Service = row.Field<string>("Service Type"),
           Adjustment = row.Field<string>("Adjustment"),
           Block = row.Field<string>("Blk"),
           AddressLine1 = row.Field<string>("Adress Line 1"),
           AddressLine2 = row.Field<string>("Adress Line 2"),
           AddressLine3 = row.Field<string>("Postal Code"),
           Usage = row.Field<decimal>("Usage"),
           Rate = row.Field<decimal>("Rate"),
           Amount = row.Field<decimal>("Amount")
        }
    );
}

--- 编辑 ---

我不确定,但我可以猜测“Bill Cycle”字段既不是 int 也不是 byte。因此,您应该将其作为字符串检索,然后将其解析为您的新对象。这是我更改的部分:

BillCycleYear = int.Parse(row.Field<string>("Bill Cycle").Substring(0, 4)),
BillCycleMonth = byte.Parse(row.Field<string>("Bill Cycle").Substring(4)),

关于c# - 如何将对象从 IEnumerable 集合添加到数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38988710/

相关文章:

c# - 如何在 ContextMenuStrip 中设置默认菜单项?

mysql - 网站连接本地数据库,如何实现远程访问?

c# - 在 MVC 中将 ASP.NET Identity 与我自己的实体结合使用

.net - 首先从 Entity Framework 模型中的模型生成数据库时如何进行迁移

c# - 用于获取用户电子邮件的 Security.Principal.IIdentity 扩展方法

c# - 如何使用 LINQ 返回包含 List<> 中最新项目的 List<>

C# LdapConnection 身份验证问题

c++ - sqlite C API,UDATE 数据库

sql - SQL order by 子句是否保证稳定(按标准)

linq - 如何获取按计数列排序的组