简体   繁体   中英

Store list of object in SQL Server using Entity Framework

I use Entity Framework to connect my SQL Server database in my C# app.

I have a Location class, which looks like this :

[Table("DBLocation")]
public class DBLocation {
    // ...
    public List<DBPicture> pictures{ get; set; }
    // ...
}

My problem is, how am I supposed to store the list into the database, do I create another table to match Location IDs and pictures, if yes how do I tell the code to use that ?

Thanks!

Your code will be something like this,

 public void savePicture(List<DBPicture> pics)
        {
            //Getting a list of pics of type DBPicture as you mentioned in class
            try
            {
                foreach(DBPicture pic in pics)
                //Using the model created from database 
                using (DataModel.PicEntities picContext = new PicEntities())
                {

                    DataModel.DBPicture dbPic = new DBPicture();
                    dbPic.idPic = pic.idPicture;
                    dbPic.idLoc = pic.idLocation;
                    picContext.Meetings.Add(dbPic);
                    picContext.SaveChanges();
                }
            }
            catch
            {

            }

        }

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