【发布时间】:2016-12-06 22:32:32
【问题描述】:
问题是当我尝试创建项目时给我这个错误
INSERT 语句与 FOREIGN KEY 约束冲突
这是我的登录操作
public ActionResult Login(UserTb U, string ReturnUrl)
{
var count = db.UsersTb.Where(x => x.NameUser == U.NameUser && x.PassUser == U.PassUser).Count();
if (count == 0)
{
ViewBag.Msg = "invalde user";
return View();
}
else
{
FormsAuthentication.SetAuthCookie(U.NameUser + "|" + U.IdUser, false);
return RedirectToAction("Index", "Home");
}
}
我想将用户 ID 传递给名为项目的表
这个表上的用户 id 名为 Uid,所以我在下面使用了这个
[Table("Item")]
public class Item
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int id { get; set; }
[Required]
public string name { get; set; }
public string info { get; set; }
public decimal price { get; set; }
public int? Uid { get; set; }
public int CatId { get; set; }
public int? CountryId { get; set; }
public int? StateId { get; set; }
public int? CityId { get; set; }
[ForeignKey("Uid")]
public virtual UserTb UserTb { get; set; }
[ForeignKey("CatId")]
public virtual Category Category { get; set; }
[ForeignKey("CountryId")]
public virtual Country Country { get; set; }
[ForeignKey("StateId")]
public virtual States States { get; set; }
[ForeignKey("CityId")]
public virtual City City { get; set; }
public Item()
{
Uid = Convert.ToInt32(HttpContext.Current.User.Identity.Name.Split('|')[1]);
}
}
这里是我的创建操作结果
public ActionResult Create()
{
var catlist = db.Categories.Select(x => new { id = x.id, name = x.name }).ToList();
SelectList sl = new SelectList(catlist.AsEnumerable(), "id", "name");
ViewBag.SelectCategories = sl;
var countrylist = db.CountryTb.Select(x => new { id = x.id, name = x.name }).ToList();
SelectList s2 = new SelectList(countrylist.AsEnumerable(), "id", "name");
ViewBag.SelectCountry = s2;
return View();
}
[HttpPost]
public ActionResult Create(Item i)
{
db.Items.Add(i);
db.SaveChanges();
return RedirectToAction("Index");
}
如果在登录时保存用户 ID 并在我需要它时在其他表上获取它而没有问题的另一种方法请告诉我如何,因为我是 mvc 中的新手
【问题讨论】:
标签: asp.net-mvc security authentication