从一个db表转换集合以添加到另一个db表

时间:2013-06-03 23:01:00

标签: asp.net-mvc entity-framework

以下是我的ActionMethod的一大块。我正在努力的部分是从 db.IntegerBuffers 中添加所有 IntegerBufferValues 的新变量整数,然后将它们添加到 db .IntegerList

        var integers = new ICollection<Integers>();

        const int COUNT = 1000000;
        Stopwatch watch = Stopwatch.StartNew();
        for (int c = 0; c < COUNT; c++)
        {
            integers = db.IntegerBuffers.OrderBy(i => i.IntegerBufferValue);
        };
        watch.Stop();

        var integerList = new IntegerList
        {
            Direction = direction,
            Performance = watch.ElapsedMilliseconds,
            Integers = integers
        };

        db.IntegerLists.Add(integerList);

IntegerList

namespace Project.Models
{
    public class IntegerList
    {
        public int IntegerListID { get; set; }
        public string Direction { get; set; }
        public long Performance { get; set; }

        public virtual ICollection<Integer> Integers { get; set; }
    }
}

IntegerBuffer

namespace Project.Models
{
    public class IntegerBuffer
    {
        public int IntegerBufferID { get; set; }
        public int IntegerBufferValue { get; set; }
    }
}

编辑:显示整数类。

整数

namespace IntegerSorterApp.Models
{
    public class Integer
    {
        public int IntegerID { get; set; }
        public int IntegerValue { get; set; }
        public int IntegerListID { get; set; }

        public virtual IntegerList IntegerList { get; set; }
    }
}

1 个答案:

答案 0 :(得分:0)

integers目前是IntegerBuffer个对象的集合。使用.Select项目用于整数:

IEnumerable<int> integers;

// ...

integers = db.IntegerBuffers
    .OrderBy(i => i.IntegerBufferValue)
    .Select(i => i.IntegerBufferValue);

或者:

integers = 
    from buffer in db.IntegerBuffers
    orderby buffer.IntegerBufferValue
    select buffer.IntegerBufferValue;

然后,您分配给集合,您可以执行以下操作:

var integerList = new IntegerList
    {
        Direction = direction,
        Performance = watch.ElapsedMilliseconds,
        Integers = integers.ToList()
    };

<强>更新

糟糕,我没有看到Integer是一个类。我的答案是创建一个Int32对象列表。基础知识仍然适用:您需要使用select来投影到您需要的任何结构。现在我不了解你的数据模型,但也许你想要这样的东西:

// Create your list first so that the list ID is saved
var integerList = new IntegerList
{
    Direction = direction,
    Performance = watch.ElapsedMilliseconds,
};
db.IntegerLists.Add(integerList);


// Now create your Integer records with the ID of the list
foreach (var buffer in db.IntegerBuffers.OrderBy(b => b.IntegerBufferValue))
{
    db.Integers.Add(new Integer
    {
        IntegerValue = buffer.IntegerBufferValue,
        IntegerListID = integerList.IntegerListID
    });
}

如果这是一对多的关系,那么在IntegerListID记录上设置Integer会隐式将其添加到列表的Integers集合中