0
votes

While I am going to add-migration it's ok but while I am going to run update-database I am getting this type of error in package manager console

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_dbo.ServiceTypes_dbo.Services_ServiceTypeID". The conflict occurred in database "Otaidea", table "dbo.Services", column 'ServicesID'.

My two model:

public class Services
{
    [Key]
    public int ServicesID { get; set; }
    [DisplayName("Register Date")]
    public DateTime RegisterDate { get; set; }

    public int ServiceTypeID { get; set; }

    public string ApplicationUserID { get; set; }
    public virtual ServiceType ServiceType { get; set; }
    public virtual ApplicationUser ApplicationUser { get; set; }

}

my another Table:

public class ServiceType
{
    [ForeignKey("Services")]
    public int ServiceTypeID { get; set; }
    public string NAME { get; set; }
    public virtual Services Services { get; set; }
}
1
The ForeignKey("Services") must go in the Services Entity, above the ServiceTypeID property - jpgrassi
i don't understand what you want to say please can you explain i am new bie - Hoque MD Zahidul
Services has ServiceType. correct? So, you don't need to reference Services inside ServiceType. You need to reference ServiceType inside Service, and also remove the ForeignKey from ServiceType - jpgrassi
can you rewrite the the two class for me because brother i am too week in english . - Hoque MD Zahidul

1 Answers

0
votes

Your relationship in your models are wrong. Services has a "Type", so the Foreign Key goes from ServiceType to Service. You don't need to reference Services inside ServiceType

You should create your model like this:

Services

public class Services
{
    [Key]
    public int ServicesID { get; set; }
    [DisplayName("Register Date")]
    public DateTime RegisterDate { get; set; }
    public string ApplicationUserID { get; set; }

    [ForeignKey("ServiceType")]
    public int ServiceTypeID { get; set; }
    public virtual ServiceType ServiceType { get; set; }

    public virtual ApplicationUser ApplicationUser { get; set; }    
}

ServiceType

public class ServiceType
{
    [Key]
    public int ServiceTypeID { get; set; }
    public string NAME { get; set; }
}

I would also do the same with the ApplicationUserID property, but since you didn't post about it I let it as is.

Also, it would be better if you drop your database and let Entity Framework create it again for you. Because you had a wrong model relationship things got "messy".