简体   繁体   English

如何在Entity Framework ASP.NET MVC中的另一个实体内部的集合中添加一个实体

[英]How to add a entity to collection inside another entity in Entity Framework asp.net mvc

I have two entities ( student , yogaspaceevent ). 我有两个实体( studentyogaspaceevent )。 Yogaspaceevent which is like a exercise class, has a collection of students as RegisteredStudents and I want to be able to add students to this event to register them. Yogaspaceevent就像一个健身班,有一组学生作为RegisteredStudents ,我希望能够将学生添加到该活动中来注册他们。

I tried a couple of things but can't seem to add a student to a yogaspaceevent, so maybe I'm not doing it correctly. 我尝试了几件事,但似乎无法将一名学生添加到Yogaspace事件中,所以也许我做得不好。

Question: do I need to create a whole new entity (say registeredstudents ) to add students to a yogaspaceevent ? 问题:我是否需要创建一个全新的实体(例如registeredstudents学生)来将学生添加到yogaspaceevent Because I thought Entity Framework would somehow create this table for me or do some other magic under the hood to add a student to a event? 因为我以为Entity Framework会以某种方式为我创建此表,或者在幕后做一些其他魔术来将学生添加到事件中? The only solution I have is to create a RegisteredStudent entity and then EF will create a table. 我唯一的解决方案是创建一个RegisteredStudent实体,然后EF将创建一个表。 Is this the right solution? 这是正确的解决方案吗?

Here are my two entities: 这是我的两个实体:

public class YogaSpaceEvent
{
    public int YogaSpaceEventId { get; set; }

    [Index] 
    public DateTime DateTimeScheduled { get; set; }
    public int AppointmentLength { get; set; }
    public int StatusEnum { get; set; }

    public virtual ICollection<Student.Student> RegisteredStudents { get; set; }   

    [Index]
    public int YogaSpaceRefId { get; set; }

    [ForeignKey("YogaSpaceRefId")]
    public virtual YogaSpace YogaSpace { get; set; }
}

public class Student
{
    public int StudentId { get; set; }
    public virtual StudentImage StudentImage { get; set; } //one-to-one
    [MaxLength(50)]
    public string CatchPhrase { get; set; }
    [MaxLength(250)]
    public string Education { get; set; } //Serra High School, San Diego State Univesity

    public string Work { get; set; } // Taco Bell, Starbucks
    [MaxLength(250)]
    public string WhyIPractice { get; set; }
    public StudentStatus Status { get; set; }
}

Here is my controller where I want to add a student to an event but I get exceptions thrown. 这是我要向事件添加学生的控制器,但会引发异常。

[HttpPost]
public ActionResult RegisterStudentForEvent(int eventId)
{
        try
        {
            Student student = _studentRepository.Find(User.Identity.GetUserId()); //User.Identity.GetUserId()
            if (student == null)
            {
                return Json( new { error = "notification", message = "You need an active student profile to register, please complete your student profile." });
            }

            var spaceEvent = _yogaSpaceEventRepository.Find(eventId);
            if (spaceEvent.RegisteredStudents == null)
            {
                spaceEvent.RegisteredStudents = new Collection<Student>(); // new EntityCollection<Student>(); neither of these two work, both throw exceptions
            }
            spaceEvent.RegisteredStudents.Add(student);

            _yogaSpaceEventRepository.Modify(spaceEvent);
            _yogaSpaceEventRepository.Save();

            // send email confirmation with a cancel link in it.

            return Json(new { error = "false", message = "Now registered!. A confirmation email has been sent. Have fun! " });
        }
        catch (Exception ex)
        {
            return Json( new { error = "true", message = ex.Message });
        }
    }

Here are the two exceptions that are thrown when I try both methods above. 这是当我尝试上述两种方法时引发的两个异常。

The object could not be added to the EntityCollection or EntityReference. 无法将该对象添加到EntityCollection或EntityReference。 An object that is attached to an ObjectContext cannot be added to an EntityCollection or EntityReference that is not associated with a source object. 无法将附加到ObjectContext的对象添加到与源对象不关联的EntityCollection或EntityReference中。

and

The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects. 无法定义两个对象之间的关系,因为它们已附加到不同的ObjectContext对象。

I was having similar issue. 我有类似的问题。

Your above code seems to be correct , I think you have missed to specify the mapping in dbcontext.cs class which resulted in below error: 您的上述代码似乎是正确的,我认为您错过了在dbcontext.cs类中指定映射的操作,这导致了以下错误:

The object could not be added to the EntityCollection or EntityReference. 无法将该对象添加到EntityCollection或EntityReference。 An object that is attached to an ObjectContext cannot be added to an EntityCollection or EntityReference that is not associated with a source object. 无法将附加到ObjectContext的对象添加到与源对象不关联的EntityCollection或EntityReference中。

I hope my below example could help you. 希望以下示例对您有所帮助。


Specialization (Parent Entity Class) 专业化(父实体类)

 [Table("M_Specialization")]
    public partial class Specialization : Entity
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        [Key]
        public int SID { get; set; }
        public string SCode { get; set; }
        public string Description { get; set; }
        public virtual ICollection<SubSpecialization> SubSpecializationDetails { get; set; }
}

Sub specialization (Child Entity Class) 子专业化(子实体类)

[Table("M_SubSpecialization")]
    public partial class SubSpecialization : Entity
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        [Key]
        public Int32 SuID { get; set; }
        public string SubCode { get; set; }
        public Int32 SID { get; set; }  // This is required in order to map between specialization and subspecialization

        [ForeignKey("SID")]
        public virtual Specialization Specialization { get; set; }
    }

dbcontext.cs: dbcontext.cs:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<SubSpecialization>().HasRequired(c => c.Specialization)
      .WithMany(s => s.SubSpecializationDetails)
      .HasForeignKey(c => c.SID);
}

You need to define a many-to-many relationship between Student and YogaSpaceEvent. 您需要在Student和YogaSpaceEvent之间定义多对多关系。 The code you have created so far represents a one-to-many relationship. 到目前为止,您创建的代码代表一对多关系。

An description of how to do that can be found here and here 有关如何执行此操作的说明,请在此处此处找到

What you need to add to your code is: - Add a ICollection property to your Student class - In your dbcontext.OnModelCreating, add code to define the many-to-many relationship. 您需要添加到代码中的是:-将ICollection属性添加到Student类中-在dbcontext.OnModelCreating中,添加代码以定义多对多关系。

As far as I can see, your controller function is OK. 据我所知,您的控制器功能正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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