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:
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; }
}
You can use Entity Framework's . AddRange method to add a collection of objects to your Db.
Add methods add a new entity to a context (instance of DbContext) which will insert a new record in the database when you call the SaveChanges() method. In the above example, context. Students. Add(std) adds a newly created instance of the Student entity to a context with Added EntityState.
Initially you find all entities whose state is not unchanged and save their entry. Then you set the state of every entity that isn't of your type TEntity and set their state to unchanged. Then call the base. SaveChanges() to save all changes to entities of your type.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With