每当我使用entityframework

时间:2015-08-24 05:02:01

标签: c# entity-framework

您好,我有一个工作简单的部门数据库,其中管理员可以添加记录(我现在唯一的功能)。

以下是我的基本代码:

上下文类:

public class DepartmentController : Controller
{

    public ActionResult Index()
    {

        EmployeeContext emp = new EmployeeContext();
       List<Department> aDep =  emp.Departments.ToList();

        return View(aDep);
    }

}

员工模型类:

[Table("carl")]
public class Employee
{


    public int id { get; set; }

    [DisplayName("First Name")]
    [Required(ErrorMessage = "First name is required")]
    public string firstname { get; set; }


    [DisplayName("Last name")]
    [Required(ErrorMessage = "Last name is required")]
    public string lastname { get; set; }


    [DisplayName("Department")]
    [Range(1, 3)]
    [Required(ErrorMessage = "Dep num is required")]
    public int department { get; set; }


}

控制器类:

public class HomeController : Controller
{
    //
    // GET: /Home/
    public ActionResult Index()
    {           
        EmployeeContext emp = new EmployeeContext();
        List<Employee> adep = emp.Employees.ToList();

        return View(adep);
    }


    [HttpGet]
    public ActionResult Create()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Create(FormCollection form)      
    {
        if (ModelState.IsValid)
        {
            try
            {
                EmployeeContext emp = new EmployeeContext();
                Employee entry = new Employee()
                {
                    firstname = form["firstname"],
                    lastname = form["lastname"],
                    department = Convert.ToInt32(form["department"])

                };

                emp.Employees.Add(entry);
                emp.SaveChanges();
            }
            catch (Exception e)
            {
                Response.Write("Failed to Add, please try again");
            }
        }      

        return View();
    }
}

我的观点只是createlist

的默认模板

我的问题在于:它们按预期工作,但有时会抛出异常并声明我无法添加记录(这是在我的catch语句中)。所以我不确定错误是来自我的代码/结构还是来自我的服务器本身。我该怎么办?

编辑:我试图再次触发错误,但它没有显示出来,我之前正在测试我的应用程序,有时我的catch语句被执行,之后我无法添加任何记录。错误是实体DLL错误。一旦我发现它,我会更新。

1 个答案:

答案 0 :(得分:0)

将部门作为整数对象传递给Employee数据对象。

 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<RegisterForComInterop>true</RegisterForComInterop>