Navigation property without foreign key, or fluent api version?

c# ef-code-first ef-migrations entity-framework entity-framework-6

Question

A user can manage another user in my table of users, albeit this is optional.int? IdManager )

[Table("users")]
public partial class User
{
    #region Properties
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    [Required]
    [Column("Id")]
    public int Id { get; set; }
    #endregion

    #region DataNavigation
    /// <summary>
    /// Navigation Id for getting parent Field
    /// WARNING: this works, but need to remove foreign key creation in migration file !
    /// </summary>
    [ForeignKey("Manager")]
    [Column("IdManager")]
    public int? IdManager { get; set; }

    /// <summary>
    /// Navigation object to parent Field
    /// </summary>
    [ScriptIgnore]
    [JsonIgnore]
    [IgnoreDataMember]
    public virtual User Manager { get; set; }
    #endregion
}

The aforementioned code now generates this in code first.

public partial class manager : DbMigration
{
    public override void Up()
    {
        AddColumn("users", "IdManager", c => c.Int());
        CreateIndex("users", "IdManager");
        AddForeignKey("users", "IdManager", "users", "Id");
    }

    public override void Down()
    {
        DropForeignKey("users", "IdManager", "users");
        DropIndex("users", new[] { "IdManager" });
        DropColumn("users", "IdManager");
    }
}

But while attempting to update the database withCannot add foreign key constraint

Nevertheless, if I remove the foreign key creation

public partial class manager : DbMigration
{
    public override void Up()
    {
        AddColumn("users", "IdManager", c => c.Int());
        CreateIndex("users", "IdManager");
    }

    public override void Down()
    {
        DropIndex("users", new[] { "IdManager" });
        DropColumn("users", "IdManager");
    }
}

When using dbContext and Linq, everything is good.

However, I have to go.[ForeignKey("Manager")] on my user object (for linq & dbcontext), which is not ideal because it will undoubtedly blow up in someone's face once more later.

Any suggestions on how I can correctly map this using Data Attributes or the Fluent API?

Thanks!

1
1
11/7/2015 7:45:03 PM

Accepted Answer

ZZZ_tmp
0
11/7/2015 7:52:33 PM

Popular Answer

ZZZ_tmp


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow