【问题标题】:Not able to Add or Update table in Entity Framework 6无法在实体框架 6 中添加或更新表
【发布时间】: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


【解决方案1】:

如果您使用 Database First,则错误表明 SampleV2 实体或表缺少主键字段或未在模型类中设置。

尝试在id 实体上添加KeyAttribute 以将其标记为主键字段:

public partial class SampleV2
{
     [Key]
     public int Id { get; set; }
     public string Name { get; set; }
     public System.DateTime DateOfBirth { get; set; }
     public bool Status { get; set; }
}

此外,您需要使用带有Set Primary Key 的表设计器在数据库中添加主键,并在EDMX 文件中将StoreGeneratedPattern 设置为Identity,然后从数据库更新生成的模型以确保映射的实体类具有标识主键字段。

注意:KeyAttribute 可以通过编辑 T4 模板 (.tt) 文件自动生成,如下所示:

<#=codeStringGenerator.UsingDirectives(inHeader: false)#>
using System.ComponentModel.DataAnnotations;
// -- other stuff

var simpleProperties = typeMapper.GetSimpleProperties(entity);
if (simpleProperties.Any())
{
    foreach (var edmProperty in simpleProperties)
    {
         if (ef.IsKey(edmProperty)) { 
    #>    [Key]
    <#    } 
    #>
    <#=codeStringGenerator.Property(edmProperty)#>
    <#
    }
}

类似问题:

Unable to update the EntitySet - because it has a DefiningQuery and no <UpdateFunction> element exist

Entity Framework 4 Error: Unable to update the EntitySet because it has a DefiningQuery

Why am I getting a "Unable to update the EntitySet because it has a DefiningQuery..." exception when trying to update a model in Entity Framework?

【讨论】:

  • StoreGeneratedPattern 已设置为仅身份。 KeyAttribute 只是不创建
  • 感谢您的效果,在执行“从数据库更新模型”后也没有将 Id 字段更改为 KeyAttribute
  • 如果您的模型生成使用 T4,我已经在上面的后半部分给出了如何在 EDMX 文件的每个模型更新时自动添加 KeyAttribute。查看此文档以获取更多详细信息:stackoverflow.com/documentation/entity-framework/4414/….
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多