Save list to database entity framework

asp.net asp.net-mvc c# entity-framework

Question

I have the following code:

 internal static bool SaveUOSChangeLog(List<Contracts.DataContracts.UOSChangeLog> values, string user)
    {
        try
        {
            using(var ctx = new StradaDataReviewContext2())
            {
                values.ForEach(u => { u.Username = user; u.Changed = DateTime.Now; });
                var test = ctx.UOSChangeLog.Add(values);
                ctx.SaveChanges();
                return true;
            }
        }

The thing I want to do Is to save values to the database. However, I get a the following error message:

enter image description here

Here is my Contracts.DataContracts.UOSChangeLog:

   public int? Id { get; set; }
        public int Accident_nr { get; set; }
        public int Refnr { get; set; }
        public int Action { get; set; }
        public string Old_data { get; set; }
        public string New_data { get; set; }
        public DateTime SearchedFromDate { get; set; }
        public DateTime SearchedToDate { get; set; }
        public DateTime Changed { get; set; }
        public string Username { get; set; }
        public string Comment { get; set; }

And here Is my Services.StradaDataReview2Model.UOSChangeLog that are used as a DbSet

[Table("UOSChangeLog")]
    public partial class UOSChangeLog
    {
        [Required]
        public int? Id { get; set; }

        public int Accident_nr { get; set; }
        [Required]
        public int Refnr { get; set; }
        [Required]
        public int Action { get; set; }
        [Required]
        public string Old_data { get; set; }
        [Required]
        public string New_data { get; set; }
        [Required]
        public DateTime SearchedFromDate { get; set; }
        [Required]
        public DateTime SearchedToDate { get; set; }
        [Required]
        public DateTime Changed { get; set; }
        [Required]
        public string Username { get; set; }
        [Required]
        public string Comment { get; set; }
    }
1
5
3/17/2016 1:31:39 PM

Accepted Answer

You're trying to add a list with the Add method which takes a single object, just keep it simple and use a foreach:

using(var ctx = new StradaDataReviewContext2())
{
   foreach(var value in values)
   {
       value.Username = user;
       value.Changed = DateTime.Now;
       ctx.UOSChangeLog.Add(value);
   }
   ctx.SaveChanges();
   return true;
}

Just use a simple foreach, linq is a querying language, not a modifying language.

4
3/17/2016 1:43:26 PM

Popular Answer

Please use addrange method.

db.TheTable.AddRange(TheList)
db.SaveChanges();


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow