实体框架数据库First Lookup表插入行

时间:2015-11-25 10:55:47

标签: c# sql-server entity-framework lookup-tables

我必须要表FundAllocation&分配

FundAllocation
    - FundAllocationId (Primary Key, Identity)
    - AllocationRefId

Allocation
    - AllocationId (Primary Key, Identity)
    - Allocation

相应的DbSets是:

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(其中FundAllocation.AllocationRefIf等于现有的AllocationId)时,它会向Allocation表添加新的Allocation。如何防止将新分配添加到数据库表中?

1 个答案:

答案 0 :(得分:0)

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

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