实体框架数据库首次查找表插入行

本文关键字:插入 查找 框架 数据库 实体 | 更新日期: 2023-09-27 18:24:12

我必须将FundAllocation&分配。

FundAllocation
    - FundAllocationId (Primary Key, Identity)
    - AllocationRefId
Allocation
    - AllocationId (Primary Key, Identity)
    - Allocation

相同的对应DbSet是:

public DbSet<FundAllocation> FundAllocation { get; set; }
public DbSet<Allocation> Allocation { get; set; }

以下是实体:

public class FundAllocation
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int FundAllocationId { get; set; }
    public int AllocationRefId { get; set; }
    [ForeignKey("AllocationRefId")]
    public virtual Allocation Allocation { get; set; }
}
public class Allocation
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int AllocationId { get; set; }
    [Column("Allocation")]
    public string AllocationTitle { get; set; }
}

分配表是一个查找表。资金分配可以具有查找表中的分配,也可以根本没有分配。但是,当我将新的FundAllocation添加到DbSet时(其中FundAllocation.AllocationRefIf等于现有的AllocationId),它会将新的Allocation添加到Allocation表中。如何防止向数据库表中新添加分配?

实体框架数据库首次查找表插入行

我当然不认为这是正确的方法,但下面的代码行对我有效:

dbContext.Entry<Allocation>(newFundAllocation.Allocation).State = EntityState.Unchanged;