I'm working at a .net core project with ef. I have two tables:
public class Asset
{
[Key]
public Guid Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
// Relationships
public ICollection<AssetMixRecord> AssetMixRecords { get; set; }
}
public class AssetMixRecord
{
public decimal Percentage { get; set; }
public Guid AssetId { get; set; }
// Relationships
public Guid ParentAssetId { get; set; }
}
The context looks like this:
modelBuilder.Entity<Asset>()
.HasMany(a => a.AssetMixRecords)
.WithOne()
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<AssetMixRecord>()
.HasKey(c => new { c.ParentAssetId, c.AssetId })
.IsClustered();
The migration code for this looks like:
migrationBuilder.CreateTable(
name: "AssetMixRecords",
columns: table => new
{
AssetId = table.Column<Guid>(nullable: false),
ParentAssetId = table.Column<Guid>(nullable: false),
Percentage = table.Column<decimal>(type: "decimal(8,7)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AssetMixRecords", x => new { x.ParentAssetId, x.AssetId })
.Annotation("SqlServer:Clustered", true);
table.ForeignKey(
name: "FK_AssetMixRecords_Assets_AssetId",
column: x => x.AssetId,
principalTable: "Assets",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
This is all nice and right. But 'ParentAssetId' also is a foreign key to 'Assets.Id'.
Our use case looks like this:
var asset1 = new Asset();
var asset2 = new Asset();
dbContext.Add(asset1);
dbContext.Add(asset2);
dbContext.SaveChanges();
var asset3 = new Asset();
asset3.AssetMixRecords.Add(new AssetMixRecord()
{
AssetId = asset1.Id,
ParentAssetId = asset3.Id
});
asset3.AssetMixRecords.Add(new AssetMixRecord()
{
AssetId = asset2.Id,
ParentAssetId = asset3.Id
});
dbContext.Add(asset3);
dbContext.SaveChanges();
I'm not able to to get this 2nd foreign key into the migration code. Should I just add it manually?
Thanks and regards
S.
Please check out my solution with complete demo, it will generate following migration. I am not sure if it is possible to have
DeleteBehavior.Cascade
with such schema, EF migration tool was complaining about circular dependency.Demo itself is below. Please notice that there are 2 navigation properties inside
Asset
. EF will load there child entities based on their location (AssetId or ParentAssetId)If you do not want to
ParentAssetId
be equal toChildAssetId
simply add code below to solution aboveYour use case will work fine if you change
AssetMixRecords
toParentAssetMixRecords
forasset3