你好,我是ASP.NET MVC中的新手。ASP.NET MVC插入兩個單獨的表
我有三個類Login
,User
和TheTradersContext
,你可以看到如下:
namespace SimpleUser.Models
{
[Table("login")]
public class Login
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[Required]
[StringLength(50)]
[Display(Name = "Email")]
public string email { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string password { get; set; }
public string status { get; set; }
public string salt { get; set; }
}
}
namespace SimpleUser.Models
{
[Table("userdata")]
public class User
{
public int ID { get; set; }
public string surname { get; set; }
public string name { get; set; }
public string sex { get; set; }
public string city { get; set; }
public string address { get; set; }
public string zipcode { get; set; }
public string tel { get; set; }
public string bdate { get; set; }
public string country { get; set; }
}
}
namespace SimpleUser.Models
{
public class TheTradersContext : DbContext
{
public DbSet<Login> loginusers { get; set; }
public DbSet<User> allusers { get; set; }
}
}
然後我創建了一個LoginController.cs具有寄存器功能中,我嘗試在兩個不同的表來傳遞我的數據庫是我從formcollection獲取的元素,如下所示。問題是在我的數據庫中只傳入表登錄名而不是用戶數據。
[HttpPost]
public ActionResult Registration(FormCollection forms){
var db = new TheTradersContext();
var crypto = new SimpleCrypto.PBKDF2();
var p = forms["password"].ToString();
String encryptPass = crypto.Compute(p);
var newUser = db.loginusers.Create();
var nuser = db.allusers.Create();
newUser.email = forms["email"].ToString();
newUser.password = encryptPass;
newUser.status = "user";
newUser.salt = crypto.Salt;
//nuser.ID=Convert.ToInt32("18");
nuser.surname = forms["lastname"].ToString();
nuser.name = forms["firstname"].ToString();
nuser.sex = forms["gender"].ToString();
nuser.city = forms["city"].ToString();
nuser.address = forms["addr"].ToString();
nuser.zipcode =forms["zip"].ToString();
nuser.tel = "fdgfdgf".ToString();
nuser.country = forms["country"].ToString();
nuser.bdate ="dsafdsaf".ToString();
try
{
db.loginusers.Add(newUser);
db.SaveChanges();
var useri = db.loginusers.Single(u => u.email == newUser.email);
if (useri == null) {
throw new Exception();
}
nuser.ID = Convert.ToInt32(useri.ID);
db.allusers.Add(nuser);
db.SaveChanges();
}
catch (Exception x)
{
ModelState.AddModelError("", "This username is in use");
}
return View();
}
我在數據庫中的表具有完全相同的用戶字段名稱。
當然,我試圖排除與登錄有關的代碼,並只傳遞數據庫中userdata的值,但我看到了異常:System.Data.Entity.Infrastructure.DbUpdateException
。
我已經嘗試了很多東西,直到現在......任何想法?
非常感謝你許多!!這對我有效......兩張桌子之間的關係不見了,我不知道我必須聲明它! – user3457458