EF - Update table without PK

现数据库有一张表tblNumbers结构如下:

CREATE TABLE [dbo].[tblNumbers](
    [Id] [NVARCHAR](20) NOT NULL,
    [Comment] [NVARCHAR](50) NULL,
UNIQUE NONCLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

在 EF 工程中,我们想增加一条记录:

static void Main(string[] args)
{
    using (var db = new TestDBEntities()) {
        var obj = new tblNumbers() { Id = "ID3", Comment = "hello" };
        db.tblNumbers.Add(obj);
        db.SaveChanges();
    }
}

执行上述程序在SaveChanges的时候会抛出异常:

Unhandled Exception: System.Data.Entity.Infrastructure.DbUpdateException: Unable to update the EntitySet 'tblNumbers' because it has a DefiningQuery and no <InsertFunction> element exists in the <ModificationFunctionMapping> element to support the current operation. ---> System.Data.Entity.Core.UpdateException: Unable to update the EntitySet 'tblNumbers' because it has a DefiningQuery and no <InsertFunction> element exists in the <ModificationFunctionMapping> element to support the current operation.

网上说对于无主键的表,默认按照视图对待,不能更新。为此,我们就创建一个Id为主键的结构相同的表,看看差异

CREATE TABLE [dbo].[tblNumbers2](
    [Id] [NVARCHAR](20) NOT NULL,
    [Comment] [NVARCHAR](50) NULL,
 CONSTRAINT [PK_tblNumbers2] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

从数据库更新模型文件(.edmx)后,打开文件,对比两个表定义:

<EntityContainer Name="TestDBModelStoreContainer">
  <EntitySet Name="tblNumbers2" EntityType="Self.tblNumbers2" Schema="dbo" store:Type="Tables" />
  <EntitySet Name="tblNumbers" EntityType="Self.tblNumbers" store:Type="Tables" store:Schema="dbo">
    <DefiningQuery>SELECT 
      [tblNumbers].[Id] AS [Id], 
      [tblNumbers].[Comment] AS [Comment]
      FROM [dbo].[tblNumbers] AS [tblNumbers]</DefiningQuery>
  </EntitySet>
</EntityContainer>

根据tblNumbers2的定义,把tblNumbers修改为:

<EntitySet Name="tblNumbers" EntityType="Self.tblNumbers" store:Type="Tables" Schema="dbo" />

保存 -> Rebuild -> 运行 -> OK