我正在开发一个从REST API获取数据的应用程序。我正在针对一个具体的类解析json,然后逐步遍历UpdateInsert(取决于该行是否存在)到SQL数据库中。其中一部分是创建一个带有SkillIdAccountId的唯一标识符列,恰当地命名为AccountSkillId。我相信我已将问题追溯到我的AddRepository部分,因为Commit有效,但是Add无效。

Add的行为就像我要传递的实体为空,但是当我在本地语言环境中查看它时,它表明它不为空:



这是我的业务层中尝试的代码

    public void GetSkills()
    {
        var dataContext = new LivePersonContext(ConfigurationWrapper.DataConnectionString);
        var apiRequest = new OAuthRequest();
        var builder = new StringBuilder("");

        using (dataContext)
        {
            var uow = new UnitOfWork(dataContext);
            var accountCredentialIds = uow.Accounts.GetAll().Select(c => c.AccountID).ToList();

            foreach (var a in accountCredentialIds)
            {
                var account = a;
                try
                {
                    builder.Clear();
                    var consumerKey = uow.Accounts.GetById(account).ConsumerKey;
                    var consumerSecret = uow.Accounts.GetById(account).ConsumerSecret;
                    var token = uow.Accounts.GetById(account).Token;
                    var tokenSecret = uow.Accounts.GetById(account).TokenSecret;
                    builder.AppendFormat(ConfigurationWrapper.SkillsUri, account);
                    var uri = builder.ToString();

                    var response = apiRequest.OauthRequestResponse(uri, consumerKey, consumerSecret, token,
                        tokenSecret);
                    if (response != null)
                    {
                        using (var reader = new StreamReader(response.GetResponseStream()))
                        {
                            var json = reader.ReadToEnd();
                            var jsonObj = JsonConvert.DeserializeObject<List<Entity.Skills>>(json);

                            var currentSkillData = uow.SkillMeta.GetAll().Select(c => c.AccountSkillId).ToList();

                            foreach (var item in jsonObj)
                            {
                                if (item.id != null)
                                {
                                    var itemId = int.Parse(item.id);
                                    var string2 = item.id + account;


                                    var accountSkillId = int.Parse(string2);

                                    if (currentSkillData.Contains(accountSkillId))
                                    {
                                        var skillUpdate = uow.SkillMeta.GetById(accountSkillId);

                                       // skillUpdate.AccountSkillID = int.Parse(accountSkillId);
                                        //skillUpdate.AccountID = account;
                                        //skillUpdate.SkillID = int.Parse(item.id);
                                        skillUpdate.Name = item.name;
                                        skillUpdate.IsDefault = item.isDefault;
                                        skillUpdate.Description = item.description;
                                        uow.Commit();
                                    }
                                    else
                                    {
                                        var addSkill = new lp_Skill_Meta
                                        {
                                            AccountSkillId = accountSkillId,
                                            AccountId = account,
                                            SkillId = itemId,
                                            Name = item.name,
                                            IsDefault = item.isDefault,
                                            Description = item.description,

                                            //TODO: Verify that they are only ever passing single values
                                            Rel = item.links[0].rel,
                                            Href = item.links[0].href
                                        };


                                            uow.SkillMeta.Add(addSkill);
                                            uow.Commit();
                                        }
                                }
                            }
                        }
                    }
                }
                catch (Exception exception)
                {
                    var lEngine = new LoggerEngine{Logger = _logger};
                    lEngine.Log("ERROR: " + exception);
                }
            }
        }
    }


这是我的存储库抽象类

 public abstract class Repository<T> : IRepository<T>
    where T : class
{
    protected  DbSet<T> _objectSet;

    public Repository(BaseContext context)
    {
        _objectSet = context.Set<T>();
    }
    #region IRepository<T> Members

    public abstract T GetById(object id);

    public IEnumerable<T> GetAll()
    {
        return _objectSet;
    }

    public IEnumerable<T> Query(Expression<Func<T, bool>>  filter)
    {
        return _objectSet.Where(filter);
    }

    public void Add(T entity)
    {
        _objectSet.Add(entity);

    }

    public void Remove(T entity)
    {
        _objectSet.Remove(entity);
    }
    #endregion
}


BaseContext是我的DAL中的DbContext抽象

这是我要添加到数据库中的实体

public class lp_Skill_Meta
{
    [Key]
    public long AccountSkillId { get; set; }

    public int AccountId { get; set; }
    public int SkillId { get; set; }
    public string Name { get; set; }
    public bool IsDefault { get; set; }
    public string Description { get; set; }
    public string Rel { get; set; }
    public string Href { get; set; }
}


这是数据库的架构:

CREATE TABLE [dbo].[lp_Skill_Meta](
    [AccountSkillId] [bigint] NOT NULL,
    [AccountId] [int] NOT NULL,
    [SkillId] [int] NOT NULL,
    [Name] [varchar](250) NULL,
    [IsDefault] [bit] NULL,
    [Description] [varchar](max) NULL,
    [Rel] [varchar](50) NULL,
    [Href] [varchar](250) NULL
) ON [PRIMARY]


如您在图片中看到的,当我将其传递给添加并尝试提交更改时,该实体不为空。但是我仍然得到:


  无法将值NULL插入表的列AccountSkillId
  `DatabaseName.dbo.lp_Skill_Meta';列不允许为空。插入
  失败。\ r \ n该语句已终止。


我一直盯着这个看了几个小时,一直在搜索,没有看到这种情况(不是说它不存在),但是任何帮助都会很棒。

更新:根据下面注释中对Jeff的SQL Trace提示,是EF试图运行的查询


  exec sp_executesql N'INSERT [dbo]。[lp_Skill]([AccountId],[SkillId],
  [名称],[IsDefault],[描述],[角色],[Href])值(@ 0,@ 1,@ 2,
  @ 3,@ 4,@ 5,@ 6)从[dbo]中选择[AccountSkillId]。[lp_Skill]在哪里
  @@ ROWCOUNT> 0 AND [AccountSkillId] = scope_identity()',N'@ 0 int,@ 1
  int,@ 2 nvarchar(max),@ 3位,@ 4 nvarchar(max),@ 5 nvarchar(max),@ 6
  nvarchar(max)'
  ,@ 0 = 10740014,@ 1 = 6,@ 2 = N'Abusers',@ 3 = 0,@ 4 = N'Abusers',@ 5 = N'self',@ 6 = N'https://sales.liveperson.net/api/account/10740014/skills/6'


AccountSkillId不是数据库中的标识列,因此为什么要抛出NULL。现在继续搜索如何使其停止将该列标记为Identity ...

最佳答案

根据这个问题:Cannot insert the value NULL into column in ASP.NET MVC Entity Framework

答案归结为将[DatabaseGenerated(DatabaseGeneratedOption.None)]添加到我的Entity时就像一个符咒。 @JeffTreuting大声喊叫我使用SQL Trace向正确的方向指出。老实说,我什至没有想到。再次感谢大家!

    public class lp_Skill
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public long AccountSkillId { get; set; }

    public int AccountId { get; set; }
    public int SkillId { get; set; }
    public string Name { get; set; }
    public bool IsDefault { get; set; }
    public string Description { get; set; }
    public string Rel { get; set; }
    public string Href { get; set; }
}

08-05 17:40