保存新记录时无法设置模型的 [Key] 属性
所以,我已经转向 MVC3,总的来说,我认为这很棒;我也非常喜欢代码优先的方法。
我今天遇到了一些麻烦,虽然在 MVC2 下我能够添加记录并编辑它们,但现在却无法这样做。
我知道这是一个模糊的开始,所以请允许我详细说明。
这是我的模型之一的示例
namespace ESF_ResourceManager.Models
{
public class FileList
{
[Key]
public int FileListID { get; set; }
[DisplayName("File title: ")]
[Required(ErrorMessage = "Please set a unique title for the file")]
// TODO: Need to add remote validation - must be unique
public string FileTitle { get; set; }
[DisplayName("Choose a File")]
[FileExtensions(Extensions = "txt, zip, pdf, ppt, xls, doc, docx, xlsx, pptx", ErrorMessage = "Please choose a valid file of type txt, zip, pdf, ppt, xls, doc, docx, xlsx or pptx")]
public HttpPostedFileBase FileUrl { get; set; }
}
}
然后相应的控制器:
namespace ESF_ResourceManager.Controllers
{
public class FileListController : ResourceManagerController
{
//
// GET: /FileList/
public ActionResult Index()
{
var fileList = from fl in DBContext.FileLists
where fl.FileListID > 0
select fl;
return View(fileList.ToList());
}
//
// GET: /FileList/Create
[HttpGet]
public ActionResult Create()
{
return View();
}
//
// POST: /FileList/Create
[HttpPost]
public ActionResult Create(FileList fileDetail)
{
if (ModelState.IsValid)
{
// test the file - size only - the file type should have been checked via Extensions as par tof the model definition
if (fileDetail.FileUrl.ContentLength > 0 && fileDetail.FileUrl.ContentLength < 1048576)
{
string fileName = Path.GetFileName(fileDetail.FileUrl.FileName);
string path = Path.Combine(Server.MapPath("~/App_Data/uploads/documents"), fileName);
fileDetail.FileUrl.SaveAs(path);
DBContext.FileLists.Add(fileDetail);
DBContext.SaveChanges();
return RedirectToAction("Index");
}
}
return View(fileDetail);
}
//
// GET: /FileList/Edit/5
[HttpGet]
public ActionResult Edit(int id)
{
var fileDetail = from fl in DBContext.FileLists
where fl.FileListID == id
select fl;
return View(fileDetail.Single());
}
//
// POST: /FileList/Edit/5
[HttpPost]
public ActionResult Edit(int id, FileList fileDetail)
{
if (ModelState.IsValid)
{
var fileEdited = DBContext.FileLists.Find(id);
UpdateModel(fileEdited);
DBContext.SaveChanges();
return RedirectToAction("Index");
}
return View();
}
//
// GET: /FileList/Delete/5
public ActionResult Delete(int id)
{
var fileDetail = from fl in DBContext.FileLists
where fl.FileListID == id
select fl;
return View(fileDetail.Single());
}
//
// POST: /FileList/Delete/5
[HttpPost]
public ActionResult Delete(int id, FileList fileDetail)
{
try
{
DBContext.FileLists.Remove(DBContext.FileLists.Find(id));
DBContext.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}
Razor 的视图是(用于创建):
@model ESF_ResourceManager.Models.FileList
@{
ViewBag.Title = "File List";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@using (Html.BeginForm("Create", "FileList", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<fieldset>
<legend>File List</legend>
<div class="editor-label">
@Html.LabelFor(model => model.FileTitle)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.FileTitle)
@Html.ValidationMessageFor(model => model.FileTitle)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.FileUrl)
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.FileUrl, new { type = "file" })
@Html.ValidationMessageFor(model => model.FileUrl)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
因此,我可以加载视图并查看输入数据的表单,但是当我单击“创建”按钮时,我得到以下消息:
值不能为空。参数名称:key
我已经查看了调试器中的对象,进入 create post 函数的对象上没有任何内容为 null。密钥是 0,而我预计(可能是错误的)它是 1。
所以我的第一个问题是我在这里错过了什么?我需要做什么才能让它正常工作?
第二个问题更笼统——我的数据在哪里?我读过的教程表明,要么在某个地方创建了 SQLExpress 数据库,要么在 App_Data 中创建了 SqlCE。我都找不到,所以我很困惑这是在哪里。
对此的任何帮助将不胜感激。
非常感谢 nathj07
编辑
感谢您过来,我仍在学习在提问时包含哪些内容会有所帮助。因此,这里是请求的项目:
数据上下文
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace ESF_ResourceManager.Models
{
public class ResourceManagerContext : DbContext
{
public DbSet<Resource> Resources { get; set; }
public DbSet<ResourceType> ResourceTypes { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<FileList> FileLists { get; set; }
}
}
Web.Config
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=152368
-->
<configuration>
<appSettings>
<add key="webpages:Version" value="1.0.0.0"/>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>
</compilation>
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages"/>
</namespaces>
</pages>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
最后 -
Views/Web.config
<?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
<section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
</sectionGroup>
</configSections>
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
</namespaces>
</pages>
</system.web.webPages.razor>
<appSettings>
<add key="webpages:Enabled" value="false" />
</appSettings>
<system.web>
<httpHandlers>
<add path="*" verb="*" type="System.Web.HttpNotFoundHandler"/>
</httpHandlers>
<!--
Enabling request validation in view pages would cause validation to occur
after the input has already been processed by the controller. By default
MVC performs request validation before a controller processes the input.
To change this behavior apply the ValidateInputAttribute to a
controller or action.
-->
<pages
validateRequest="false"
pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<controls>
<add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" />
</controls>
</pages>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<remove name="BlockViewHandler"/>
<add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
</handlers>
</system.webServer>
</configuration>
如果还有其他需要看到了,我会很乐意将其发布。
谢谢 nathj07
编辑 2 我现在尝试手动添加 SQLExpress 数据库并更新 web.config 文件中的连接字符串。
<connectionStrings>
<remove name="LocalSqlServer"/>
<add name="LocalSqlServer" connectionString="Data Source=.\SQLExpress;Integrated Security=True;AttachDBFilename=|DataDirectory|DB_ESF_ResourceManager.mdf;User Instance=true" />
</connectionStrings>
这让我犯了同样的错误——没有任何区别。我对此完全不知所措,不知道下一步该去哪里。对此还有更多建议吗?
谢谢 纳斯吉07
So, I've moved to MVC3 and on the whole I think this great; I really like the codefirst approach too.
I have run into a bit of bother today with this and while under MVC2 I was able to add records and edit them I am now unable to do so.
I know that is a vague start so allow me to eloborate.
Here is an example of one of my models
namespace ESF_ResourceManager.Models
{
public class FileList
{
[Key]
public int FileListID { get; set; }
[DisplayName("File title: ")]
[Required(ErrorMessage = "Please set a unique title for the file")]
// TODO: Need to add remote validation - must be unique
public string FileTitle { get; set; }
[DisplayName("Choose a File")]
[FileExtensions(Extensions = "txt, zip, pdf, ppt, xls, doc, docx, xlsx, pptx", ErrorMessage = "Please choose a valid file of type txt, zip, pdf, ppt, xls, doc, docx, xlsx or pptx")]
public HttpPostedFileBase FileUrl { get; set; }
}
}
Then the corresponding controller:
namespace ESF_ResourceManager.Controllers
{
public class FileListController : ResourceManagerController
{
//
// GET: /FileList/
public ActionResult Index()
{
var fileList = from fl in DBContext.FileLists
where fl.FileListID > 0
select fl;
return View(fileList.ToList());
}
//
// GET: /FileList/Create
[HttpGet]
public ActionResult Create()
{
return View();
}
//
// POST: /FileList/Create
[HttpPost]
public ActionResult Create(FileList fileDetail)
{
if (ModelState.IsValid)
{
// test the file - size only - the file type should have been checked via Extensions as par tof the model definition
if (fileDetail.FileUrl.ContentLength > 0 && fileDetail.FileUrl.ContentLength < 1048576)
{
string fileName = Path.GetFileName(fileDetail.FileUrl.FileName);
string path = Path.Combine(Server.MapPath("~/App_Data/uploads/documents"), fileName);
fileDetail.FileUrl.SaveAs(path);
DBContext.FileLists.Add(fileDetail);
DBContext.SaveChanges();
return RedirectToAction("Index");
}
}
return View(fileDetail);
}
//
// GET: /FileList/Edit/5
[HttpGet]
public ActionResult Edit(int id)
{
var fileDetail = from fl in DBContext.FileLists
where fl.FileListID == id
select fl;
return View(fileDetail.Single());
}
//
// POST: /FileList/Edit/5
[HttpPost]
public ActionResult Edit(int id, FileList fileDetail)
{
if (ModelState.IsValid)
{
var fileEdited = DBContext.FileLists.Find(id);
UpdateModel(fileEdited);
DBContext.SaveChanges();
return RedirectToAction("Index");
}
return View();
}
//
// GET: /FileList/Delete/5
public ActionResult Delete(int id)
{
var fileDetail = from fl in DBContext.FileLists
where fl.FileListID == id
select fl;
return View(fileDetail.Single());
}
//
// POST: /FileList/Delete/5
[HttpPost]
public ActionResult Delete(int id, FileList fileDetail)
{
try
{
DBContext.FileLists.Remove(DBContext.FileLists.Find(id));
DBContext.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}
The view which is Razor is (for create):
@model ESF_ResourceManager.Models.FileList
@{
ViewBag.Title = "File List";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@using (Html.BeginForm("Create", "FileList", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<fieldset>
<legend>File List</legend>
<div class="editor-label">
@Html.LabelFor(model => model.FileTitle)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.FileTitle)
@Html.ValidationMessageFor(model => model.FileTitle)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.FileUrl)
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.FileUrl, new { type = "file" })
@Html.ValidationMessageFor(model => model.FileUrl)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
So, I can load the view and see the form to enter the data but when I click the Create button I get the following message:
Value cannot be null. Parameter name: key
I have looked at the object in the debugger and nothing on the object coming into the create post function is null. the key is 0 and I would have expected (possibly wrongly) for this to be 1.
So my first question is what have I missed here? What do I need to do to get this to work properly for me?
The second question is more general - where is my data? The tutorials I have read on this suggest that ther eis either a SQLExpress database created some place or a SqlCE in the App_Data. Neither of which I can find so I'm confused as to where this is.
Any help on this would be greatly appreciated.
Many thanks
nathj07
EDIT
Thanks for stopping by, I'm still learning what would be helpful to include when asking questions. So, here are the requested items:
Data Context
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace ESF_ResourceManager.Models
{
public class ResourceManagerContext : DbContext
{
public DbSet<Resource> Resources { get; set; }
public DbSet<ResourceType> ResourceTypes { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<FileList> FileLists { get; set; }
}
}
Web.Config
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=152368
-->
<configuration>
<appSettings>
<add key="webpages:Version" value="1.0.0.0"/>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>
</compilation>
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages"/>
</namespaces>
</pages>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
And finally -
Views/Web.config
<?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
<section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
</sectionGroup>
</configSections>
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
</namespaces>
</pages>
</system.web.webPages.razor>
<appSettings>
<add key="webpages:Enabled" value="false" />
</appSettings>
<system.web>
<httpHandlers>
<add path="*" verb="*" type="System.Web.HttpNotFoundHandler"/>
</httpHandlers>
<!--
Enabling request validation in view pages would cause validation to occur
after the input has already been processed by the controller. By default
MVC performs request validation before a controller processes the input.
To change this behavior apply the ValidateInputAttribute to a
controller or action.
-->
<pages
validateRequest="false"
pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<controls>
<add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" />
</controls>
</pages>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<remove name="BlockViewHandler"/>
<add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
</handlers>
</system.webServer>
</configuration>
If there is anything else you need to see then I'll happily post it up.
Thanks
nathj07
Edit 2
I have now tried adding a SQLExpress database manually and updating the connection string in the web.config file.
<connectionStrings>
<remove name="LocalSqlServer"/>
<add name="LocalSqlServer" connectionString="Data Source=.\SQLExpress;Integrated Security=True;AttachDBFilename=|DataDirectory|DB_ESF_ResourceManager.mdf;User Instance=true" />
</connectionStrings>
This leaves me with the same error - no difference at all. I'm at a complete loss with this and have no idea where to go next with it. Are there any more suggestions on this?
Thanks
nathj07
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
EF 似乎没有将您的密钥标记为身份列。如果类型为
int
、short
或long
,且名称为,则实体框架将属性标记为主键;ID
。在您的型号上,“ID”部分为大写。您有两种可能的解决方案:[DatabaseGenerate(DatabaseGenerateOption.Identity)]
放置在您的属性上方,以表明它实际上是一个标识列FileListID
重命名为FileListId
。如果您选择此解决方案,您可能也不再需要[Key]
属性。如果您选择第一个解决方案,您的属性将如下所示:
It seems that EF doesn't mark your key as an identity column. Entity Framework marks a property as a primary key if the type is
int
,short
orlong
, and the name is<classname>Id
. On your model, the 'ID' part is in upper case. You have two possible solutions:[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
above your property, to indicate that it is in fact an identity columnFileListID
toFileListId
. You'll probably won't need the[Key]
attribute anymore either if you go for this solution.If you go for the first solution, your property will look like this:
您还需要为 mvc make bind 添加 FileListID
you need too add FileListID for the mvc make bind
你的第二个问题:
因为你的 web.config 文件中没有任何连接字符串,所以如果数据库不存在,Entity Framework 4.1 将尝试在 SQL Server Express 实例中创建一个新数据库。该数据库的名称是 Namespace.DerivedContextName,因此在您的情况下它应该是:ESF_ResourceManager.Models.ResourceManagerContext。
您可以使用 SQL Server Management Studio 或在 Visual Studio 中通过服务器资源管理器查看数据库。
您的第一个问题:
您收到错误的一个可能原因是数据库中与模型中的关键属性
FileListID
相对应的关键列未标记为标识列,即自动标记为的列当您插入新行时生成自己的值。您的模型配置假设该列是一个标识(默认情况下,您没有将其关闭)。因此,当您插入新对象时,EF 不会将FileListID
的值发送到数据库,因为它假定数据库将创建一个值。如果数据库中的列不是标识,它不会创建值,并且您会收到异常。因此,您应该在数据库中检查
FileListID
是否是标识列,如果不是,则将其打开。Your second question:
Because you don't have any connection string in your web.config file Entity Framework 4.1 will try to create a new database in your SQL Server Express instance if the database doesn't exist. The name of this database is Namespace.DerivedContextName, so in your case it should be: ESF_ResourceManager.Models.ResourceManagerContext.
You can take a look at the database with SQL Server Management Studio or in Visual Studio via the Server Explorer.
Your first question:
A possible reason why you get your error is that the key column in the database corresponding to the key property
FileListID
in your model is not marked as an identity column, i.e. as a column which automatically generates its own value when you insert a new row. Your model configuration assumes that the column is an identity (by default, you didn't switch that off). As a consequence EF won't send a value forFileListID
to the database when you insert a new object because it assumes that the database will create a value. If the column in the database isn't an identity it doesn't create a value and you get your exception.So, you should check in the DB if
FileListID
is an identity column and if not, turn that on.