无法插入,标识插入关闭
本文关键字:插入 标识 | 更新日期: 2023-09-27 18:17:13
这似乎很简单,但我不能得到它的工作。我有两个表,Organization
和Season
。
Organization
表可以有一个活动的季节集,这个季节必须用Organization
集创建。
Organization
class (table)
public class Organization
{
public int ID { get; set; }
public string Name { get; set; }
[Display(Name = "Active Season")]
public int? ActiveSeasonID { get; set; }
public virtual Season ActiveSeason { get; set; }
}
Season
class (table)
public class Season
{
public int ID { get; set; }
public int OrganizationID { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime StartDate { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime EndDate { get; set; }
public string Name { get; set; }
public virtual Organization organization { get; set; }
}
给我这个错误:
无法确定类型"ResultzSys.DAL"之间关联的主体结束。"Organization"answers"ResultzSys.DAL.Season"。该关联的主体端必须使用关系流畅API或数据注释显式配置。
我用这个来定义这两个
之间的关系modelBuilder.Entity<Organization>()
.HasOptional(s => s.ActiveSeason).WithRequired(d => d.organization);
但是当我尝试添加一个季节时,我得到
当IDENTITY_INSERT设置为OFF时,不能在表'Season'中插入标识列的显式值
抛出错误的控制器代码:
public async Task<ActionResult> Create([Bind(Include = "ID,OrganizationID,StartDate,EndDate,Name")] Season season)
{
if (ModelState.IsValid)
{
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ResultzContext()));
var currentUser = manager.FindById(User.Identity.GetUserId());
season.OrganizationID = currentUser.OrganizationID;
db.Seasons.Add(season);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
}
我就是不明白为什么它不让我创造赛季记录…任何提示都很感激。
谢谢
根据这篇MSDN文章,您应该在标识列上使用DatabaseGenerated
属性:
[DatabaseGenerated(DatabaseGenerationOption.Identity)]
public int ID { get; set; }