简体   繁体   中英

Entity Framework Posting records

I've got this model:

public class FinalizedWebinarAttendeesList
{
    public List<FinalizedWebinar> Webinars { get; set; }
}

public class FinalizedWebinar
{
    public int ParticipantID { get; set; }
    public bool AffidavitRecvd { get; set; }
    public string EventCode { get; set; }
}

And this DbContext:

public class webinarFinalizedAttendeesListDbContext : DbContext
{
    public webinarFinalizedAttendeesListDbContext(string nameOrConnectionString) : base(nameOrConnectionString) { }
    public DbSet<FinalizedWebinar> WebinarFinalAttendee { get; set; }
}

I'd like to send the entire FinalizedWebinarAttendeesList to a function vs. having to send each of them (like below). Is this possible?

public void InsertAttendee(FinalizedWebinar aa)
{
    using (webinarFinalizedAttendeesListDbContext context = new webinarFinalizedAttendeesListDbContext(connectionString))
    {
        context.WebinarFinalAttendee.Add(aa);
        context.SaveChanges();
    }
}

Sure, why not ? Adapt this example to better fit your needs :

public void InsertAttendee(List<FinalizedWebinar> webinars)
{
    using (webinarFinalizedAttendeesListDbContext context = new webinarFinalizedAttendeesListDbContext(connectionString))
    {
        foreach(var webinar in webinars) {
            context.WebinarFinalAttendee.Add(webinar);
        }

        context.SaveChanges();
    }
}

A context in Entity Framework will remember all changes to tracked objects and apply them all at once when saved. You can perform as many operations as you wish inside the context.

Note: pushing this to the extreme will likely have an undesirable performance impact, but as long as you're doing a reasonable amount of work, everything should be fine. As always, measure for performance impacts if you're worried there's a problem.

Do you want something like DbSet.AddRange() ? You can add items to an IEnumerable and add the IEnumerable to your DbSet.

DbSet<T> has an .AddRange(IEnumerable<T>) method that you can use:

context.WebinarFinalAttendee.AddRange(attendees);

More info at https://msdn.microsoft.com/en-us/library/system.data.entity.dbset.addrange(v=vs.113).aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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