简体   繁体   中英

Connecting 2 tables to a third using C# EF6

I am using C# & EF6 trying to connect two diffirent tables ( Chassis & BodyType ) to another table ( StockItem ). But I am getting this error while trying to update my database via the Package Manager Console :

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_dbo.Chassis_dbo.StockItems_ChassisLongitudinalId". The conflict occurred in database "TruckDbWcf", table "dbo.StockItems", column 'Id'.

My code-first classes:

Chassis:

public class Chassis
{
    public int Id { get; set; }
    public string Name { get; set; }

    public int ChassisLongitudinalId { get; set; }
    [ForeignKey("ChassisLongitudinalId")]
    public virtual StockItem ChassisLongitudinal { get; set; }
}

BodyType:

public class BodyType
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool isFlatDeck { get; set; }

    public int LongitudinalId { get; set; }
    [ForeignKey("LongitudinalId")]
    public virtual StockItem Longitudinal { get; set; }
}

StockItem:

public class StockItem
{
    public StockItem()
    {
        SectionGroups = new HashSet<SectionGroup>();
    }
    public int Id { get; set; }


    private string _stockCode;
    [Index(IsUnique = true)]
    [StringLength(450)]
    [Required]
    public string StockCode
    {
        get { return _stockCode; }
        set { _stockCode = value.ToUpper(); }
    }

    public string Description { get; set; }

    public virtual ICollection<SectionGroup> SectionGroups { get; set; }

    public double? Mass { get; set; }

    public double UnitCost { get; set; }

    public override string ToString()
    {
        return StockCode + " - " + Description;
    }
}

There already is data in the database, and I have tried to update-database -force the database but its giving me the same error.

I know I'm missing something small and simple, but I can't figure out what it is. Any help would be great thank you! - Regards the EF6 rookie.

Probably Your Chassis table has some rows already inserted. In one migration you are trying to create non nullable foreign key. I think, You should be nullable foreign key.

public int? LongitudinalId { get; set; }
public int? ChassisLongitudinalId { get; set; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM