保存具有由外键链接的集合的实体时出现EF错误

时间:2016-02-25 11:27:56

标签: c# mysql entity-framework

我的问题是以下问题。

我收到此消息的EF异常:

  

操作失败:无法更改关系,因为   一个或多个外键属性是不可为空的。当一个   改变了关系,相关的外键属性是   设置为空值。如果外键不支持空值,   必须定义新的关系,外键属性必须是   分配了另一个非空值,或者不相关的对象必须是   删除。

对于此异常,我可以自己弄清楚EF正在尝试将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;
        }

为什么它不起作用。

1 个答案:

答案 0 :(得分:0)

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

<style name="MyAlertDialogMaterialStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
        <!-- Used for the buttons -->
        <item name="colorAccent">@color/md_teal_900</item>
        <!-- Used for the title and text -->
        <item name="android:textColorPrimary">@color/white</item>
        <!-- Used for the background -->
        <item name="android:background">@color/color_primary_dark</item>
    </style>