添加新对象,修改新对象,一起保存可以吗?
添加新对象,修改新对象,一起保存可以吗?
下边代码我测试过,没有出错,但是不知道是否规范
db.Library.AddObject(book); //保存Library对象
docMove.FileCounter = FileCounter; //记录文件计数器对象
docMove.DirCounter = DirCounter;
db.SaveChanges();
using (var db = new WEBVODEntities())
{
DocBatchMove docMove;
if (!Directory.Exists(rootParth))
{
Directory.CreateDirectory(rootParth); //新一天上传前的初始化.
docMove = db.DocBatchMove.SingleOrDefault(a => a.Id == 1);
docMove.DirCounter = 1; //目录从1开始
docMove.FileCounter = 0; //文件数从0开始
db.SaveChanges(); //保存到计数数据表 DocBatchMove
}
FileInfo[] files = new DirectoryInfo(txtSource.Text).GetFiles();
foreach (FileInfo f in files) //遍历文件数组
{
#region 遍历文件数组
docMove = db.DocBatchMove.SingleOrDefault(a => a.Id == 1); //获取记录信息
FileCounter = docMove.FileCounter + 1; //从 数据表DocBatchMove 取文件计数器
DirCounter = docMove.DirCounter; //从 数据表DocBatchMove 取目录计数器
if (FileCounter > 50) //每个文件夹文件数不超过50
{
FileCounter = 1; //大于50,重新计数
DirCounter = DirCounter + 1; //生产新的文件夹
}
strGuid = Guid.NewGuid().ToString(); //获得唯一编号
SaveParth = rootParth + DirCounter.ToString() + "\" + strGuid + "\"; //完整的保存路径
Directory.CreateDirectory(SaveParth); //新建保存PDF的目录
f.CopyTo(SaveParth + Constants.BookPdfName); //拷贝文件到目录
Library book = new Library();
book.Title = f.Name;
book.CategoryID = 7;
book.Guid = strGuid;
book.Status = Constants.BookStatus_PDF;
book.LoginName = Constants.UserAdmin;
book.PubDate = DateTime.Now;
book.TimeBook = DTPick1.Value; //期刊需要 分期(时间)
book.Extension = f.Extension;
book.VirDir = virDir + DirCounter.ToString() + "\" + strGuid + "\"; //虚拟目录
db.Library.AddObject(book); //保存Library对象
docMove.FileCounter = FileCounter; //记录文件计数器
docMove.DirCounter = DirCounter;
db.SaveChanges();
#endregion
}
}