【问题标题】:How do i call my mapper method who returns a List<>我如何调用返回 List<> 的映射器方法
【发布时间】:2012-04-04 12:36:10
【问题描述】:

我正在尝试从我的映射器返回一个对象列表并将它们保存到我的实体框架数据库中。 我的映射器类看起来像这样

    class TimereportMappers
    {        
    public List<Days> dayMap(List<Day> days)
    {
        List<Days> output = new List<Days>();

        foreach (Common.Day input in days)
        {
            output.Add(new Days()
            {
                Date = input.Date,
                Hour = input.Hours
            });
            //output.Date = input.Date;
            //output.Hour = input.Hours;
        }

        return output;
    }

}

我的数据访问类中的问题是我不知道如何将对象保存到我的数据库中,数据访问类中的方法看起来像这样

     public void sendDays(List<Common.Day> days)
        {
            TimereportMappers mapper = new TimereportMappers();
            context.Days.AddObject(mapper.dayMap(days));         
            context.SaveChanges();
        }

但是 AddObject 只能添加 1 个对象?如何添加对象列表?

Visual Studio 给了我错误代码

错误 2 参数 1:无法从 'System.Collections.Generic.List' 转换为 'Timereport.BusinessLogic.Data_Access.Days' C:\Users\widde\Documents\Visual Studio 2010\Projects\Timereport\Timereport.BusinessLogic \TimereportDataAccess.cs 43 37 Timereport.BusinessLogic

错误 1 ​​'System.Data.Objects.ObjectSet.AddObject(Timereport.BusinessLogic.Data_Access.Days)' 的最佳重载方法匹配有一些无效参数 C:\Users\widde\Documents\Visual Studio 2010\Projects\ Timereport\Timereport.BusinessLogic\TimereportDataAccess.cs 43 14 Timereport.BusinessLogic

【问题讨论】:

    标签: c# entity-framework list mapper


    【解决方案1】:

    这行得通吗? (我无法对此进行明显测试,但想法是一次只添加 1 个对象实例,而不是整个列表)

    sendDays 方法:

    public void sendDays(List<Common.Day> days)
    {
        TimereportMappers mapper = new TimereportMappers();
    
        foreach (var day in days)
        {
            context.Days.AddObject(mapper.dayMap(day));
        }
    
        context.SaveChanges();
    }
    

    TimereportMappers 类:

    class TimereportMappers
    {
        public Days dayMap(Day input)
        {
            return new Days
            {
                Date = input.Date,
                Hour = input.Hours
            };
        }
    
    }
    

    【讨论】:

    • 是的,这个想法是正确的,现在可以了。我只需要更改一些代码以适应我的项目。感谢您花时间回答我的问题
    【解决方案2】:

    调用AddObject() mutil-times 并调用SaveChanges() 一次?

    【讨论】:

    • 一次也不可能调用。在第一条消息中更新了错误代码
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-22
    • 1970-01-01
    • 1970-01-01
    • 2021-02-17
    • 2022-07-21
    • 1970-01-01
    相关资源
    最近更新 更多