【发布时间】:2017-04-04 10:16:24
【问题描述】:
我正在尝试使用 Entity Framework 6 插入和更新表。我做不到。
当我插入时,我得到一个错误
无法更新 EntitySet 'SampleV2',因为它有一个 DefiningQuery 并且元素中不存在支持当前操作的元素
当我更新时,抛出的错误是:
属性“名称”是对象的关键信息的一部分,不能修改。
我的代码:
//Table script
CREATE TABLE [dbo].[SampleV2](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](150) NOT NULL,
[DateOfBirth] [datetime] NOT NULL,
[Status] [bit] NOT NULL
) ON [PRIMARY]
// SampletV2.cs
public partial class SampleV2
{
public int Id { get; set; }
public string Name { get; set; }
public System.DateTime DateOfBirth { get; set; }
public bool Status { get; set; }
}
// Utilities.cs
public static Dictionary<bool,string> SavePlayerDetails(SampleV2 model)
{
Dictionary<bool, string> dicInfo = new Dictionary<bool, string>();
if (model.Id == 0)
{
try
{
SampleV2 sam = new SampleV2
{
Name = model.Name,
DateOfBirth = model.DateOfBirth,
Status = model.Status
};
using (var _context = new ExamEntities1())
{
_context.SampleV2.Add(sam);
_context.SaveChanges(); // getting error here
}
}
catch (Exception e)
{
throw;
}
}
else
{
try
{
using (var _context = new ExamEntities1())
{
SampleV2 data = _context.SampleV2.SingleOrDefault(a => a.Id == model.Id);
data.DateOfBirth = model.DateOfBirth;
data.Name = model.Name;
data.Status = model.Status;
_context.Entry(data).State = System.Data.Entity.EntityState.Modified; // getting error here
_context.SaveChanges();
}
}
catch (Exception e)
{
throw;
}
}
return dicInfo;
}
【问题讨论】:
-
尝试在数据库中添加
id作为主键和KeyAttribute,因为错误表明目标表上缺少主键。 -
模型已经动态创建,要手动添加KeyAttribute吗?
-
你有复合PK吗?
-
不,我没有复合PK
-
您使用过 EDMX 吗?尝试在数据库和模型上添加主键 - 请注意,EF 支持一个主键而不是复合(同一张表中有多个主键)。
标签: asp.net-mvc c#-4.0 entity-framework-6