简体   繁体   English

EF6创建新实体,而不只是设置参考

[英]EF6 creates new entity instead of setting just a reference

I'd like to save a List of flags for each event. 我想为每个事件保存标志列表。 In order to get this done I'm using the following method in my Controller: 为了做到这一点,我在控制器中使用以下方法:

 public ActionResult CreateEvent(Models.Event newEvent)
 {
     if(!string.IsNullOrEmpty(Request.Form["flag"]))
     {
         string[] idArr = Request.Form["flag"].Split(',');
         foreach(string idString in idArr)
         {
             int id = idString.ToInt32();
             newEvent.Flags.Add(_applicantRepository.GetFlagByID(id));
         }
     }
     _applicantRepository.SaveEvent(newEvent);
 }

In my ApplicantRepository I use the following methods: 在我的ApplicantRepository中,我使用以下方法:

 public void SaveEvent(Event ev)
 {
     using (var dbCtx = new VisitorRegistrationContext())
     {
         dbCtx.Events.AddOrUpdate(ev);
         dbCtx.SaveChanges();
     }
 }

 public Models.Flag GetFlagByID(int id)
 {
     using (var dbCtx = new VisitorRegistrationContext())
     {
         Models.Flag flag = dbCtx.Flags.Find(id);
         return flag;
     }
 }

Unfortunately, each time I save an Event some new flags will be created. 不幸的是,每次我保存一个事件时,都会创建一些新的标志。 Even though they already exist (with the same id). 即使它们已经存在(具有相同的ID)。

在此处输入图片说明

These are my models: 这些是我的模型:

public class Event
{
    public Event()
    {
        Users = new List<Usr>();
        Type = new EventType();
        Flags = new List<Flag>();
    }

    public int ID { get; set; }

    [Required]
    [Display(Name = "Event")]
    public string EventName { get; set; }
    public string Comment { get; set; }

    [Required]
    public EventType Type { get; set; }
    public ICollection<Flag> Flags { get; set; }
}

and

public class Flag
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public bool IsInactive { get; set; }

    public virtual ICollection<Event> Events { get; set; }


}

How can I tell EF to simple set the reference in my intermediate table called FlagEvent? 如何告诉EF在我的中间表FlagEvent中简单地设置引用?

You need to use the same context, for example: 您需要使用相同的上下文,例如:

public void CreateEvent(Event newEvent)
{
    var flags = "1,2,3";
    string[] idArr = flags.Split(',');
    using (var ctx = new Context())
    {
        foreach (string idString in idArr)
            newEvent.Flags.Add(ctx.GetFlagByID(Convert.ToInt32(idString)));
        ctx.Events.AddOrUpdate(newEvent);
        ctx.SaveChanges();
    }
}

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

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