I am coding a simple MVC 5 internet application. Here are my models:
public class House
{
[Key]
public int Id { get; set; }
public string name { get; set; }
public virtual ICollection<Room> rooms { get; set; }
public int itemId { get; set; }
public virtual Item item { get; set; }
public House()
{
rooms = new List<Room>();
}
}
public class Room
{
[Key]
public int Id { get; set; }
public int roomNumber { get; set; }
public int houseId { get; set; }
public virtual House house { get; set; }
public int itemId { get; set; }
public virtual Item item { get; set; }
}
public class Item
{
[Key]
public int Id { get; set; }
public string name { get; set; }
}
When I load the Index action result in the House controller, I am getting this error:
Introducing FOREIGN KEY constraint 'FK_dbo.Rooms_dbo.Items_itemId' on table 'Rooms' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint or index. See previous errors.
Can I please have some help to code this correctly?
Thanks in advance
EDIT
I have now added the ForeignKey
attribute to the fields foreign key fields:
public class House
{
[Key]
public int Id { get; set; }
public string name { get; set; }
public virtual ICollection<Room> rooms { get; set; }
public int itemId { get; set; }
[ForeignKey("itemId")]
public virtual Item item { get; set; }
public House()
{
rooms = new List<Room>();
}
}
public class Room
{
[Key]
public int Id { get; set; }
public int roomNumber { get; set; }
public int houseId { get; set; }
[ForeignKey("houseId")]
public virtual House house { get; set; }
public int itemId { get; set; }
[ForeignKey("itemId")]
public virtual Item item { get; set; }
}
public class Item
{
[Key]
public int Id { get; set; }
public string name { get; set; }
}
I am still getting the same error.