1

使用 LINQ to SQL 插入数据,生成 id 但数据库表为空。

使用存储过程没有问题。但是使用 linq 插入每次都会生成 id 但表是空的。

代码如下:

Int32 t = 2;

using (EduDataClassesDataContext db =new EduDataClassesDataContext())
{
    using (var scope = new TransactionScope())
    {
        db.Connection.ConnectionString = Common.EdukatingConnectionString;
        UserLogin userlog = new UserLogin();
        userlog.Username = userinfo.Username;
        userlog.Password = userinfo.Password;
        userlog.UserTypeId = t;
        userlog.FullName = userinfo.FullName;
        db.UserLogins.InsertOnSubmit(userlog);
        db.SubmitChanges();
        Int64 n = userlog.Id;
        UserInformation userinfor = new UserInformation();
        userinfor.FirstName = userinfo.FirstName;
        userinfor.LastName = userinfo.LastName;
        userinfor.MobileNum = userinfo.MobileNum;
        userinfor.Email = userinfo.Email;
        userinfor.Gender = userinfo.Gender;
        userinfor.Address = userinfo.Address;

        userinfor.UserLoginId = n;
        userinfor.CreatedBy = n;
        userinfor.OrganizationName = userinfo.OrganizationName;
        userinfor.DateOfBirth = userinfo.DateOfBirth;
        userinfor.CreatedDate = DateTime.Now;
        db.UserInformations.InsertOnSubmit(userinfor);
        db.SubmitChanges();
    }
}
4

1 回答 1

2

当您使用 时TransactionScope,您需要调用Complete方法才能在数据库中提交事务。

using (var db = new EduDataClassesDataContext())
using (var scope = new TransactionScope())
{
    ...
    db.UserInformations.InsertOnSubmit(userinfor);
    db.SubmitChanges();

    // The Complete method commits the transaction. If an exception has been thrown,
    // Complete is not  called and the transaction is rolled back.
    scope.Complete();
}

未能调用此方法会中止事务,因为事务管理器将此解释为系统故障或事务范围内抛出的异常。

于 2013-10-10T09:32:34.977 回答