c# - 使用外键链接的集合保存实体时出现 EF 错误

标签 c# mysql entity-framework

我的问题是以下一个。

我收到了带有此消息的 EF 异常:

The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.

对于这个异常,我可以自己弄清楚 EF 正在尝试将 null 值设置为不可为 null 类型的 int 字段。

这是我的上下文:

[DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))]
    public class RealEstDBContext : DbContext
    {
        #region Constructors
        public RealEstDBContext() 
            : base("RealEstDBContext")
        {

        }
        #endregion

        #region DBSets
        public DbSet<Caracteristic> Caracteristics { get; set; }
        public DbSet<CaracteristicGroup> CaracteristicGroups { get; set; }
        public DbSet<Parameter> Parameters { get; set; }
        public DbSet<Property> Properties { get; set; }
        public DbSet<PropertyType> ProertyTypes { get; set; }
        public DbSet<Caption> Captions { get; set; }
        #endregion
    }

然后是我的模型:

   public class CaracteristicGroup
    {
        public CaracteristicGroup()
        {
            Caracteristics = new List<Caracteristic>();
        }
        #region Properties
        public int Id { get; set; }
        [Required]
        [MaxLength(50)]
        public string Name { get; set; }
        public string Description { get; set; }
        public virtual ICollection<Caracteristic> Caracteristics {get; set; }
        #endregion
    }

public class Caracteristic
    {
        #region Properties
        public int Id { get; set; }
        [Required]
        [MaxLength(50)]        
        public string Name { get; set; }
        public string Description { get; set; }
        [Required]
        [ForeignKey("Group")]
        public int GroupId { get; set; }
        [ForeignKey("GroupId")]
        public virtual CaracteristicGroup Group { get; set; }
        #endregion
    }

如果我尝试保存一个不包含任何特征关联的特征组,一切都运行良好,但我该组包含一个特征 EF 去抛出异常。

这是保存组的代码。

[HttpPost]
        public JsonResult SaveGroup(CaracteristicGroup caracteristicGroup)
        {
            JsonResult toReturn = new JsonResult();
            toReturn.JsonRequestBehavior = JsonRequestBehavior.AllowGet;

            try
            {

                if (ModelState.IsValid)
                {

                    var oldCaracteristicGroup = UnitOfWork.Instance.DataContext.CaracteristicGroups.Include(c => c.Caracteristics).Where(p => p.Id == caracteristicGroup.Id).FirstOrDefault();

                    if (oldCaracteristicGroup == null)
                        UnitOfWork.Instance.DataContext.CaracteristicGroups.Add(caracteristicGroup);
                    else
                    {



                        oldCaracteristicGroup.Name = caracteristicGroup.Name;
                        oldCaracteristicGroup.Description = caracteristicGroup.Description;
                        UnitOfWork.Instance.DataContext.Entry(oldCaracteristicGroup).State = EntityState.Modified;


                        foreach (Caracteristic item in oldCaracteristicGroup.Caracteristics)
                            UnitOfWork.Instance.DataContext.Entry(item).State = EntityState.Modified;
                    }

                    UnitOfWork.Instance.SubmmitWriteChanges();


                    toReturn.Data = new
                    {
                        Success = true,
                        Message = "Caracteristic group Saved",
                        Content = oldCaracteristicGroup != null ? oldCaracteristicGroup.Id : caracteristicGroup.Id
                    };
                }
                else
                {
                    string errorMsg = string.Empty;

                    foreach (var state in ModelState)
                        foreach (var error in state.Value.Errors)
                            errorMsg += error.ErrorMessage + Environment.NewLine;

                    toReturn.Data = new
                    {
                        Success = false,
                        Message = errorMsg,
                        Content = ""
                    };
                }
            }
            catch(Exception ex)
            {
                toReturn.Data = new
                {
                    Success = false,
                    Message = "An critical erros has ocur in the server. Call your administrator",
                    Content = ""
                };
            }

            return toReturn;
        }

为什么它不起作用。

最佳答案

您不需要自己添加 [ForeignKey] 属性。尝试将您的特征模型更改为此:

public class Caracteristic
{
    #region Properties

    public int Id { get; set; }

    [Required]
    [MaxLength(50)]        
    public string Name { get; set; }

    public string Description { get; set; }

    public int CaracteristicGroupId { get; set; }

    public virtual CaracteristicGroup Group { get; set; }

    #endregion
}

关于c# - 使用外键链接的集合保存实体时出现 EF 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35625984/

相关文章:

C#:从其基类的实例返回继承类(泛型列表)

c# - 如何在 Silverlight 4 中绑定(bind) ContextMenu 的 IsEnabled 属性?

php - 从php中的日期中提取时间并存储在mysql中

sql - 用最高值批量替换更多表中的值

c# - SQL Server 到 Entity Framework 数据类型的映射

c# - 如何否定 IQueryable 的 Where 子句

c# - 使用 WEB API 和 Entity Framework 项目的 IIS 本地计算机上的 "The underlying provider failed to Open"异常

c# - 测试sql连接而不抛出异常

MySQL 如何对带有连接的查询执行 COUNT(*)?

asp.net - 初始化数据库时出现异常