Entity Framework Errors When Trying to Create Many-to-Many Relationships
This is a quit question: 2 foreign keys in one table using entity structure
I am trying to figure out my relationship in these tables:
public class Event
{
public int EventId { get; set; }
public string EventName { get; set; }
public string EventLocation { get; set; }
public string EventType { get; set; }
public string EventDate { get; set; }
public virtual ICollection<Dog> Dogs { get; set; }
public virtual ICollection<Result> Results { get; set; }
}
public class Dog
{
public int DogId { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public bool Checked { get; set; }
public string DogImage { get; set; }
[ForeignKey("Event")]
public int EventId { get; set; }
public virtual ICollection<Merit> Merits { get; set; }
public virtual ICollection<Result> Results { get; set; }
public virtual Event Event { get; set; }
}
public class Result
{
public int ResultId { get; set; }
public int Track { get; set; }
public int Obedience { get; set; }
public int Protection { get; set; }
[ForeignKey("Dog")]
public int DogId { get; set; }
public virtual Dog Dog { get; set; }
[ForeignKey("Event")]
public int EventId { get; set; }
public virtual Event Event { get; set; }
}
From what I understand from the original question, I don't need my Event class to be able to hold a collection of dogs. Is it going over my head? I do not understand how to properly set this up so that each dog participates in many activities and for each event it will receive a score related to that particular event.
I also have this method in mine dbContext
:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Event>()
.HasRequired(c => c.Results)
.WithMany()
.WillCascadeOnDelete(false);
}
The error that occurs when trying to create an event is as follows:
Foreign key "FK_dbo.Dogs_dbo.Events_EventID" refers to an invalid table "dbo.Events".
Failed to create constraint. See previous errors.
Thank!
EDIT:
I used to use this code to add dogs to an event:
[HttpPost]
public ActionResult DogsInEvent(DogsInEventVm model)
{
var choosenEvent = _ef.SingleEvent(model.ChoosenEvent.EventId);
choosenEvent.Dogs = new Collection<Dog>();
choosenEvent.Dogs = model.Dogs.Where(o => o.Checked).ToList();
_ef.AddDogsToEvent(choosenEvent);
return RedirectToAction("AllEvents");
}
Of course, this is not possible as my event no longer contains a list of dogs. Am I really right here? How can I link the dog list to the event?
source to share
No one has answered this question yet
See similar questions:
or similar: