每当我尝试更新模型并使用实体框架保存更改时,您收到以下异常。而对于我的生活,我无法弄清楚导致异常的原因。 DataContext Attach方法引发了此异常。
虽然在stackoverflow和其他地方有关于这个特殊异常的类似帖子,但是我所看到的所有内容都集中在删除父节点而没有在父子关系的配置上指定级联删除时。但每当我尝试更新此模型时抛出异常,因此让我对异常的原因感到困惑。
操作失败:无法更改关系,因为一个或多个外键属性不可为空。当对关系进行更改时,相关的外键属性将设置为空值。如果外键不支持空值,则必须定义新关系,必须为外键属性分配另一个非空值,或者必须删除不相关的对象。
这是模型
public class FreelanceJob : IEntity
{
//Private members
private ICollection<Bid> _bids;
private ICollection<Skill> _skills;
public string Title { get; set; }
public string Description { get; set; }
public int PostedById { get; set; }
public virtual Profile PostedBy { get; set; }
public int ViewCount { get; set; }
public int CategoryId { get; set; }
public virtual Category Category { get; set; }
/// <summary>
/// Specificies a user can apply to (or bid on) this job
/// </summary>
public bool CanApply { get; set; }
public JobType JobType { get; set; }
/// <summary>
/// This represents the target geographical
/// location this job is being targeted at
/// </summary>
public JobScope JobScope { get; set; }
public DateTime PostedOn { get; set; }
public bool IsAwarded { get; set; }
/// <summary>
/// This is used to identify jobs that has
/// not been completed by the job owner,
/// and thereby should not be listed as a new job.
/// </summary>
public bool IsDefinitionCompleted { get; set; }
[NotMapped]
public ObjectState ObjectState { get; set; }
public int Id { get; set; }
public byte[] TimeStamp { get; set; }
public decimal MiniumPrice { get; set; }
public decimal MaximumPrice { get; set; }
public bool IsFreelanceCompleted { get; set; }
public virtual ICollection<Bid> Bids
{
get { return _bids ?? (_bids = new List<Bid>()); }
protected set { _bids = value; }
}
public virtual ICollection<Skill> Skills
{
get { return _skills ?? (_skills = new List<Skill>()); }
set { _skills = value; }
}
}
这是代码优先配置
HasKey(a => a.Id);
Property(a => a.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(a => a.Description).IsRequired().HasMaxLength(20000);
Property(a => a.Title).IsRequired().HasMaxLength(1000);
Property(a => a.PostedOn).IsRequired();
Property(a => a.TimeStamp).IsRowVersion();
HasRequired(a => a.PostedBy).WithMany(a => a.PostedFreelanceJobs).HasForeignKey(a => a.PostedById);
HasRequired(a => a.Category).WithMany(a => a.FreelanceJobs).HasForeignKey(a => a.CategoryId);
Property(a => a.MaximumPrice).IsRequired();
Property(a => a.MiniumPrice).IsRequired();
Property(a => a.TimeStamp).IsRowVersion();
HasMany(a => a.Bids)
.WithRequired(a => a.PlacedOnFreelanceWork)
.HasForeignKey(a => a.PlaceOnFreelanceWorkId);
HasMany(a => a.Skills).WithMany(a => a.FreelanceJobs);