简体   繁体   中英

Converting a string into a List and then using Entity Framework to insert into Database

I am converting a string into a list and then trying to use entity framework to insert it into a DB. The issue that I am having is that I don't know how to save the changes to the DB.

This is the code that I am trying to use and is where the string is converted to a list:

if (intCounter == 0)
{
    return JsonConvert.DeserializeObject<List<foo>>(jsonString).Cast<T>().ToList();
}

Then in a seperate class below.

ConvertJson.Convert<CouncilEvent>(strResponseJSONContent, intCounter);

The Entity Framework Model that I am trying to use for the list.

namespace foo.Models
{
    public partial class foo
    {
        public foo()
        {
            this.EventDates = new List<EventDate>();
        }

        public System.Guid foo_PK { get; set; }
        public string EntityID { get; set; }
        public string Address1 { get; set; }
        public string Address2 { get; set; }
        public string Address3 { get; set; }
        public bool Adult { get; set; }
    }
}

The class foo contains properties that match those in the string.

It is this foo that I am then trying to insert into the DB. foo is also part of my Entity Framework model.

I have never used a list in this situation before and I thought it would just be a matter of using db.SaveChanges() but that doesn't seem to work. Where would I place the necessary lines of code such as using (db = new contextFoo) and db.SaveChanges() . Also do I need to add the items? I haven't because I thought I was already adding them to the class and therefore didn't need to do this manually?

db.SaveChanges() will only 'update' your database to what was changed. So, you need to add something to the database, and then call SaveChanges() for it to work.

You can loop the list to add the objects to the context, then call SaveChanges() ...

var councilEvents = ConvertJson.Convert<CouncilEvent>(strResponseJSONContent, intCounter);

using (var db = new contextFoo()) 
{
    foreach (var councilEvent in councilEvents)
    {
        db.CouncilEvents.Add(councilEvent);
    }
    db.SaveChanges();
}

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