实体框架核心 - 外键1(额外的外键列)

时间:2017-09-26 23:23:27

标签: c# entity-framework ef-model-first

我刚刚升级到Entity Framework Core 2,现在我遇到了一个额外的列存在问题,并且有一个唯一的密钥,即使它不在我的模型中,也没有在其他地方定义。

索引:

migrationBuilder.CreateTable(
    name: "Vouchers",
    columns: table => new
    {
        Id = table.Column<int>(nullable: false)
            .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
        Code = table.Column<Guid>(nullable: false),
        IsClaimed = table.Column<bool>(nullable: false),
        LastModified = table.Column<DateTime>(nullable: false),
        NumberOfUnits = table.Column<int>(nullable: false),
        TransactionId = table.Column<int>(nullable: false),
        TransactionId1 = table.Column<int>(nullable: true) // why is this here?
    },
    constraints: table =>
    {
        table.PrimaryKey("PK_Vouchers", x => x.Id);
        table.ForeignKey(
            name: "FK_Vouchers_Transactions_TransactionId1",
            column: x => x.TransactionId1,
            principalTable: "Transactions",
            principalColumn: "Id",
            onDelete: ReferentialAction.Restrict);
    });

TransactionId1不在模型中:

public class Voucher : IAutoLastModified
{
    public int Id { get; set; }
    public DateTime LastModified { get; set; }

    public int TransactionId { get; set; }
    public Transaction Transaction { get; set; }

    public int NumberOfUnits { get; set; }
    public Guid Code { get; set; }
    public bool IsClaimed { get; set; }
}

我是否错误地定义了外键?

modelBuilder.Entity<Voucher>().HasOne(x => x.Transaction).WithOne(x => x.Voucher).IsRequired(false);

我的应用程序失败,因为TransactionId1始终为null并且具有我无法删除的唯一约束。

为什么EF为此表创建了一个额外的列?

6 个答案:

答案 0 :(得分:0)

您需要告诉模型构建器您要将voucher表中的哪一列用作外键列。否则,Entity Framework将为您创建一个。

为此,请在流畅的设置中添加HasForeignKey方法:

modelBuilder.Entity<Voucher>().HasOne(x => x.Transaction).WithOne(x => x.Voucher).HasForeignKey<Voucher>(x => x.TransactionId).IsRequired(false);

注意在设置一对一关系时,您需要将外键所在的实体定义为通用约束。

答案 1 :(得分:0)

好的,所以我弄清楚问题是什么(对于那些犯了同样错误的人,请保留这个问题。)

我将该关系标记为可选,但该列为int而不是int?,因此EF决定在幕后添加它自己的列。

修复此问题后,我不得不重新创建数据库 - 由于现有数据,迁移未成功完成。

答案 2 :(得分:0)

过去我使用数据优先方法遇到过这个问题。我不得不删除现有的列但是每次更新后该列都出现在edmx架构结构中,我必须手动删除它才能使其工作。你可以重新创建edmx而不是更新。

答案 3 :(得分:0)

我有同样的问题,我的修复是在导航属性上方添加[ForeignKey(&#34;&#34;)]的DataAnnotation标记,以明确说明要使用哪一个。

public Guid TransactionId { get; set; }

[ForeignKey("TransactionId ")]
public Transaction Transaction { get; set; }

由于

答案 4 :(得分:0)

如果您以双向绑定方式定义模型,但忘记流畅地使用它,也会发生这种情况:

public class Customer
{
    public Guid Id { get; set; }
    public List<Order> Orders {get; set;}
}

public class Order
{
    public Guid Id { get; set; }

    public Guid CustomerId { get; set; }
    public Guid Customer { get; set; }
}

// AppDbContext
builder.Entity<Order>()
     .HasOne(x => x.Customer)
     .WithMany() //WRONG -> should be .WithMany(x => x.Orders) OR modify the model to not define the collection at the customer entity
     .HasForeignKey(x => x.CustomerId)
     .OnDelete(DeleteBehavior.SetNull)
;

答案 5 :(得分:0)

当子级中的外键字段类型与父级中的主键字段类型不匹配时,我遇到了这个问题。

示例:

public class User // Parent
{
    public long Id { get; set; }
    public virtual ICollection<UserLike> UserLikes { get; set; } // Child collection
}

public class UserLike // Child
{
    public int Id { get; set; }
    public int UserId { get; set; } // Foreign key
    public virtual User User { get; set; } // Navigation property
}

DbContext 中,我有:

modelBuilder.Entity<UserLike>(entity =>
{
    entity.HasOne(x => x.User)
    .WithMany(x => x.UserLikes)
    .OnDelete(DeleteBehavior.ClientCascade);
}

此处,int UserId与父级中的主键long Id类型不匹配。解决方案是使UserId long

public class UserLike // Child
{
    public int Id { get; set; }
    public long UserId { get; set; } // Foreign key
    public virtual User User { get; set; } // Navigation property
}
相关问题