0

嗨朋友们,我有下面的清单

List<Authors>listAuthor=new  List<Authors>();

在那个列表中我有 100 条记录,现在我的问题是我想在 Asp.Net MVc 中使用实体框架中的数据库优先技术将这些列表保存到数据库中,只需要一次往返(只有一次命中数据库)

我创建了对象

  Author objAuthor=new Author();
  objAuthor=listAuthor;

我收到转换错误,有什么想法的朋友吗?

这是我的完整代码

    public ActionResult SaveAuthorConsol()
    {
        List<Author> listAuthor = new List<Author>(); // declare list

        List<Bib> bib = new List<Bib>(); // geting records from this table
        bib = db.Bibs.ToList();

        var q = db.Authors.ToList(); 

        foreach (var c in q)
        {
            db.Authors.DeleteObject(c); //Note:deleting previous records from Author table
        }

        db.SaveChanges();

        foreach (var bibitems in bib) // return Author type list 
        {
            Authors objAuthor = new Authors();
           listAuthor.AddRange(objAuthor.SaveAouthor(0, bibitems.Contents));
        }
        foreach (Author objauthor in listAuthor) //adding my list records to database
        {
            db.Authors.Attach(objauthor); //   getting error here
        }


        db.SaveChanges();
        return View();
    }

谢谢

4

3 回答 3

2

您不必创建类型的新对象Author。将每个项目添加到数据库上下文后,您可以直接调用 SaveChanges 一次。

尝试:

foreach(Author objAuthor in listAuthor)
{
     db.Author.AddObject(objAuthor);
}
db.SaveChanges();
于 2012-09-17T06:26:57.643 回答
1

您可以将元素添加到列表中:

List<Authors> listAuthor = new List<Authors>();
Author objAuthor = new Author();
listAuthor.Add(objAuthor);

但既然你提到了 EF,我猜你有一个数据库上下文,你可以直接向其中添加实体并持久化更改:

Author objAuthor = new Author();
db.Authors.Add(objAuthor);
db.SubmitChanges();
于 2012-09-17T06:25:09.793 回答
0

问题在于您的转换方式..看看您的代码,您要做的是..将aList<Authors>分配给Author类的实例..这根本不可能..您必须做相反的事情..

编辑 多个更新不幸的是,还没有办法。我可以建议你做什么..为你的多行准备 XML。并使用 XML insert 并使用 Regular Stored Procedure ,通过这种方式,您可以一次性插入任意数量的行,并且只能在 One Hit to DB 中插入。

于 2012-09-17T06:31:19.317 回答