A dependent property in a ReferentialConstraint is mapped to a store-generated column

后端 未结 13 1495
终归单人心
终归单人心 2020-11-27 17:23

I get this error when writing to the database:

A dependent property in a ReferentialConstraint is mapped to a store-generated column. Column: \'Paym

13条回答
  •  清歌不尽
    2020-11-27 18:05

    In my case, I had a Database Generated property, and a ForeignKey navigation property set up to reference a 1 to 1 related table.

    This wasn't something I could remove, I needed to be able to both set the primary key of the entity to be Database Generated AND I needed to be able to reference the 1 to 1 table as a navigation property.

    Not sure if this is the same for others, but this problem was only showing up when creating a new entity, reading or editing existing entities did not exhibit the issue, so I got around the issue by creating an inherited version of my Context and using the Fluent method to switch off the navigation property when creating.

    So, my original entity looked like this:

    public partial class MyEntity
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public Guid id{ get; set; }
    
    
        // Navigation
        [ForeignKey("id")]
        public PathEntity Path { get; set; }
    }
    

    So I made a special inherited context that looked like this:

        private class _navPropInhibitingContext : EF.ApplicationDBContext
        {
            protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                base.OnModelCreating(modelBuilder);
    
                modelBuilder.Entity()
                    .Ignore(e => e.Path);
    
            }
        }
    

    and then changed the code that created the new entity to make user of the new context type

        using (var specialContext = new _navPropInhibitingContext())
        {
            var dbModel = new MyEntity() 
            {
                ...
            };
    
            specialContext.MyEntity.Add(dbModel);
            await specialContext.SaveChangesAsync();
        }
    

    Hope this helps somebody

提交回复
热议问题