2016-09-26 52 views
1

這是我試圖將數據保存到我的表時得到的錯誤。我在MVC中創建了腳手架。填寫表單中的數據後,當我點擊創建按鈕,發生下面的錯誤

錯誤:

An exception of type 'System.Data.Entity.Infrastructure.DbUpdateException' occurred in EntityFramework.dll but was not handled in user code

Additional information: Unable to update the EntitySet ' CustormerD ' because it has a DefiningQuery and no <InsertFunction> element exists in the <ModificationFunctionMapping> element to support the current operation.

控制器代碼:

[HttpPost] 
[ValidateAntiForgeryToken] 
public ActionResult Create([Bind(Include="custid,name,cell_No,address,date,time,serviceNo")] CustormerD custormerd) 
{ 
    if (ModelState.IsValid) 
    { 
     db.CustormerDs.Add(custormerd); 
     db.SaveChanges(); 
     return RedirectToAction("Index"); 
    } 
    return View(custormerd); 
} 

見下表代碼:

public partial class CustormerD 
{ 
    public int custid { get; set; } 
    public string name { get; set; } 
    public Nullable<int> cell_No { get; set; } 
    public string address { get; set; } 
    public Nullable<System.DateTime> date { get; set; } 
    public Nullable<System.TimeSpan> time { get; set; } 
    public Nullable<int> serviceNo { get; set; } 
} 

SQL代碼

CREATE TABLE [dbo].[CustormerD](
[custid] [int] IDENTITY(1,1) NOT NULL, 
[name] [nchar](20) NULL, 
[cell_No] [int] NULL, 
[address] [nchar](20) NULL, 
[date] [date] NULL, 
[time] [time](7) NULL, 
[serviceNo] [int] NULL 
) ON [PRIMARY] 
+0

如果您的表沒有主鍵,則可能會發生此錯誤! –

+2

在'custid'上添加'[Key]' –

+0

可否請我協助我在我的數據庫表中失敗的地方 – sibonile

回答

1

按在評論OP使用討論.edmx文件。

所以,你可以設置主鍵的表像下:

USE [yourdatbase] 
GO 

/****** Object: Table [dbo].[CustormerD] Script Date: 26/09/2016 4:08:23 PM ******/ 
SET ANSI_NULLS ON 
GO 

SET QUOTED_IDENTIFIER ON 
GO 

CREATE TABLE [dbo].[CustormerD](
    [custid] [int] IDENTITY(1,1) NOT NULL, 
    [name] [nchar](20) NULL, 
    [cell_No] [int] NULL, 
    [address] [nchar](20) NULL, 
    [date] [date] NULL, 
    [time] [time](7) NULL, 
    [serviceNo] [int] NULL, 
CONSTRAINT [PK_CustormerD] PRIMARY KEY CLUSTERED 
(
    [custid] ASC 
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] 
) ON [PRIMARY] 

GO 

設置主鍵後,您應該更新與數據庫的.edmx模型。

0

如果字段的名稱是模型+ ID的名稱,則實體框架將僅從模型中承擔主鍵。否則,你將不得不明確指出哪個字段用作主鍵。對於你的模型,這將意味着要麼改變你的主鍵的名稱:

public int CustomerDID { get; set; } 

實體框架將隨後自動承擔起它作爲主鍵。另外,您使用[關鍵]如下標記您的主鍵:

public partial class CustormerD 
{ 
    [Key] 
    public int custid { get; set; } 
    public string name { get; set; } 
    public Nullable<int> cell_No { get; set; } 
    public string address { get; set; } 
    public Nullable<System.DateTime> date { get; set; } 
    public Nullable<System.TimeSpan> time { get; set; } 
    public Nullable<int> serviceNo { get; set; } 
} 
相關問題