簡體   English   中英

如何在Entity Framework ASP.NET MVC中的另一個實體內部的集合中添加一個實體

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

我有兩個實體( studentyogaspaceevent )。 Yogaspaceevent就像一個健身班,有一組學生作為RegisteredStudents ,我希望能夠將學生添加到該活動中來注冊他們。

我嘗試了幾件事,但似乎無法將一名學生添加到Yogaspace事件中,所以也許我做得不好。

問題:我是否需要創建一個全新的實體(例如registeredstudents學生)來將學生添加到yogaspaceevent 因為我以為Entity Framework會以某種方式為我創建此表,或者在幕后做一些其他魔術來將學生添加到事件中? 我唯一的解決方案是創建一個RegisteredStudent實體,然后EF將創建一個表。 這是正確的解決方案嗎?

這是我的兩個實體:

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; }
}

這是我要向事件添加學生的控制器,但會引發異常。

[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 });
        }
    }

這是當我嘗試上述兩種方法時引發的兩個異常。

無法將該對象添加到EntityCollection或EntityReference。 無法將附加到ObjectContext的對象添加到與源對象不關聯的EntityCollection或EntityReference中。

無法定義兩個對象之間的關系,因為它們已附加到不同的ObjectContext對象。

我有類似的問題。

您的上述代碼似乎是正確的,我認為您錯過了在dbcontext.cs類中指定映射的操作,這導致了以下錯誤:

無法將該對象添加到EntityCollection或EntityReference。 無法將附加到ObjectContext的對象添加到與源對象不關聯的EntityCollection或EntityReference中。

希望以下示例對您有所幫助。


專業化(父實體類)

 [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; }
}

子專業化(子實體類)

[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:

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

您需要在Student和YogaSpaceEvent之間定義多對多關系。 到目前為止,您創建的代碼代表一對多關系。

有關如何執行此操作的說明,請在此處此處找到

您需要添加到代碼中的是:-將ICollection屬性添加到Student類中-在dbcontext.OnModelCreating中,添加代碼以定義多對多關系。

據我所知,您的控制器功能正常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM