Asp.net mvc 从一个db表强制转换集合以添加到另一个db表
下面是我的ActionMethod的一部分。我正在努力解决的部分是从db.IntegerBuffers中使用所有integerBufferValue强制转换一个新变量integers,然后将它们添加到db.IntegerListAsp.net mvc 从一个db表强制转换集合以添加到另一个db表,asp.net-mvc,entity-framework,Asp.net Mvc,Entity Framework,下面是我的ActionMethod的一部分。我正在努力解决的部分是从db.IntegerBuffers中使用所有integerBufferValue强制转换一个新变量integers,然后将它们添加到db.IntegerList var integers = new ICollection<Integers>(); const int COUNT = 1000000; Stopwatch watch = Stopwatch.Start
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);
编辑:显示整数类
整数
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; }
}
}
integers
当前是IntegerBuffer
对象的集合。使用。选择将其投影为整数:
IEnumerable<int> integers;
// ...
integers = db.IntegerBuffers
.OrderBy(i => i.IntegerBufferValue)
.Select(i => i.IntegerBufferValue);
然后,分配给集合,可以执行以下操作:
var integerList = new IntegerList
{
Direction = direction,
Performance = watch.ElapsedMilliseconds,
Integers = integers.ToList()
};
// 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
});
}
更新:
哎呀,我没有看到Integer
是一个类。我的答案是创建Int32
对象的列表。基本原理仍然适用:您需要使用select来投影到所需的任何结构。现在,我不理解您的数据模型,但您可能希望这样:
var integerList = new IntegerList
{
Direction = direction,
Performance = watch.ElapsedMilliseconds,
Integers = integers.ToList()
};
// 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
});
}
如果这是一对多关系(看起来是这样),那么在Integer
记录上设置IntegerListID
将隐含地将其添加到列表的Integers
集合中。回答得好,谢谢。但是,integers.ToList()返回错误:无法将类型“System.Collections.Generic.List”隐式转换为“System.Collection.Generic.ICollection”。我已在上面进行了编辑以显示Integer类。也许这个名字不好。请参阅我的更新。我假设Integer
的IntegerListID
属性表示一个外键,而IntegerList
的Integers
集合只是一个导航属性。