Adding values from List<T> to database column - c#

Currently, I can insert a record which contains the second, minute, hour, Repeat, JobId and UserID, however, it will only insert one value from each of the List<object>.
Question 1:
How do I add values from a List<object> (model.DayOfMonth, model.Month and model.DaysOfWeek) into the local database?
Question 2:
Also, to my understanding, each value in the list should have their own record. How would I create a new record for each value in the List<object> (named above) while copying over the same second, minute, hour, repeat, JobId and UserID.
Controller:
[HttpPost]
public ActionResult ScheduleInfo(Values model, int JobList1, string Second, string Minute, string Hour, object DayOfMonth, object Month, object DaysOfWeek, int repeatTime)
{
var secondCon = Convert.ToInt32(Second);
var minuteCon = Convert.ToInt32(Minute);
var hourCon = Convert.ToInt32(Hour);
model.Job = JobList1;
model.Second = secondCon;
model.Minute = minuteCon;
model.Hour = hourCon;
model.DayOfMonth = new List<object>();
model.Month= new List<object>();
model.DaysOfWeek = new List<object>();
foreach (var dofm in model.DofMInfo)
{
if (dofm.IsChecked)
{
model.DayOfMonth.Add(dofm.DofMID);
}
}
foreach (var month in model.MonthInfo)
{
if (month.IsChecked)
{
model.Month.Add(month.monthID);
}
}
foreach (var day in model.DayInfo)
{
if (day.IsChecked)
{
model.DaysOfWeek.Add(day.dayID);
}
}
model.repeatTime = repeatTime;
try
{
ScheduleEntity db = new ScheduleEntity();
AspNetUser aspNetUser = new AspNetUser();
Job job = new Job();
Schedule sched = new Schedule();
sched.Second = Convert.ToString(model.Second);
sched.Minute = Convert.ToString(model.Minute);
sched.Hour = Convert.ToString(model.Hour);
//foreach (var day in model.DayOfMonth)
//{
// sched.DayOfMonth = Convert.ToString(day);
//}
//foreach (var month in model.Month)
//{
// sched.Month = Convert.ToString(month);
//}
//foreach (var weekday in model.DaysOfWeek)
//{
// sched.DayOfWeek = Convert.ToString(weekday);
//}
sched.Repeat = 4;
sched.JobId = 2;
sched.AspNetUsersId = User.Identity.GetUserId();
db.Schedules.Add(sched);
db.SaveChanges();
}
catch (Exception ex)
{
throw ex;
}
return RedirectToAction("SchedulerIndex");
}
}
The Schedule class I'm calling and setting as sched:
using System;
using System.Collections.Generic;
public partial class Schedule
{
public int ScheduleID { get; set; }
public string Second { get; set; }
public string Minute { get; set; }
public string Hour { get; set; }
public string DayOfMonth { get; set; }
public string Month { get; set; }
public string DayOfWeek { get; set; }
public string AspNetUsersId { get; set; }
public Nullable<int> JobId { get; set; }
public int Repeat { get; set; }
public virtual AspNetUser AspNetUser { get; set; }
public virtual Job Job { get; set; }
}

Related

Error on Edit Object in entityframework An entity object cannot be referenced by multiple instances of Entity ChangeTracker

I get an error when I call this text in my project. An entity object cannot be referenced by multiple instances of Entity Change Tracker.
public static short Udf_Edit_Invoice(tblInvoice inv)
{
using (DbContextModel db = new DbContextModel())
{
using (DbContextTransaction transaction = db.Database.BeginTransaction())
{
try
{
if (db.Entry<tblInvoice>(inv).State == EntityState.Detached)
{
db.Set<tblInvoice>().Attach(inv);
}
db.Entry<tblInvoice>(inv).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
transaction.Commit();
return 1;
}
catch(Exception ee)
{
transaction.Rollback();
return 0;
}
}
}
}
Click Event: (And you can see the click event as follows, which was called inside a form and the information of the main class and the child class is poured into it, and then the editing command is called, which I encounter an error.)
tblInvoice invtPub = new tblInvoice();
private void Btn_Save_Click(object sender, EventArgs e)
{
if (TxtTax.Text == "")
{
TxtTax.Text = "0";
}
Decimal Dec_TotalPrice = 0;
Decimal Dec_TotalTakhfif = 0;
Entities.Entity.tblInvoiceDetail invdObj;
List<Entities.Entity.tblInvoiceDetail> invd = new List<Entities.Entity.tblInvoiceDetail>();
foreach (DataRow Row in FactDt.Rows)
{
invdObj = new Entities.Entity.tblInvoiceDetail();
Dec_TotalPrice += Decimal.Parse(Row["FoodTotalPrice"].ToString());
Dec_TotalTakhfif += Decimal.Parse(Row["FoodDiscount"].ToString());
invdObj.AssetID = int.Parse(Row["FoodID"].ToString());
invdObj.AssetQuantity = Double.Parse(Row["FoodQuantity"].ToString());
invdObj.Discount = Double.Parse(Row["FoodDiscount"].ToString());
invdObj.UnitPrice = Double.Parse(Row["FoodUnitPrice"].ToString());
invdObj.InvoiceID = 0;
invdObj.TotalPrice = Double.Parse(Row["FoodTotalPrice"].ToString());
invd.Add(invdObj);
}
invtPub.CreatorUserID = BLL.Class_GlobalVars.ThisPUserID;
invtPub.CustomerID = long.Parse(Txt_CustomerCode.Text.Trim());
invtPub.DateOfFactor = DateTime.Now;
invtPub.InvoiceTitleID = 0;
invtPub.IsCanceled = false;
invtPub.PayCardOfInvoice = Decimal.Parse(Txt_Card.Text.Trim());
invtPub.PayCashOfInvoice = Decimal.Parse(Txt_Cach.Text.Trim());
invtPub.PayCredOfInvoice = (Decimal.Parse(Txt_Debit.Text.Trim()) < 0 ? Decimal.Parse(Txt_Debit.Text.Trim()) : 0);
invtPub.PayDebtOfInvoice = (Decimal.Parse(Txt_Debit.Text.Trim()) >= 0 ? Decimal.Parse(Txt_Debit.Text.Trim()) : 0);
invtPub.ShamsiDateOfFactor = ShamsiTools.Class_SHamsiTools.UDF_MiladiDateToShmasi(DateTime.Now);
invtPub.StrDescription = Txt_Description.Text.Trim();
invtPub.TaxOfInvoice = Decimal.Parse(TxtTax.Text.Trim());
invtPub.TotalPriceOfFactor = Dec_TotalPrice;
invtPub.TotalPriceOfFactorWithTax = (Decimal.Parse(TxtTax.Text) + Dec_TotalPrice);
invtPub.tblInvoiceDetail = invd;
if (Entities.Classes.Class_tblInvoice.Udf_Edit_Invoice(invtPub) == 1)
{
Lbl_Total_Aglam.Text = "0";
Lbl_Total_Price.Text = "0";
Lbl_Total_Takhfif.Text = "0";
GrPr_Mohasebeh.Enabled = false;
Grpr_Custumer.Enabled = true;
Grpr_Factor.Enabled = true;
FactDt.Rows.Clear();
for (int i = FactDt.Rows.Count - 1; i >= 0; i--)
{
DataRow dr = FactDt.Rows[i];
{
dr.Delete();
}
}
Grd_Factor.DataSource = FactDt;
MessageBox.Show("Edited . . . . . .");
UDF_TXTFactorClear();
UDF_TXTCustomerClear();
}
else
{
}
}
and total error message:
An entity object cannot be referenced by multiple instances of IEntityChangeTracker.
"EntityFramework"
at System.Data.Entity.Core.Objects.ObjectContext.VerifyContextForAddOrAttach(IEntityWrapper wrappedEntity)
at System.Data.Entity.Core.Objects.ObjectContext.AttachSingleObject(IEntityWrapper wrappedEntity, EntitySet entitySet)
at System.Data.Entity.Core.Objects.ObjectContext.AttachTo(String entitySetName, Object entity)
at System.Data.Entity.Internal.Linq.InternalSet`1.<>c__DisplayClassa.<Attach>b__9()
at System.Data.Entity.Internal.Linq.InternalSet`1.ActOnSet(Action action, EntityState newState, Object entity, String methodName)
at System.Data.Entity.Internal.Linq.InternalSet`1.Attach(Object entity)
at System.Data.Entity.Internal.InternalEntityEntry.set_State(EntityState value)
at System.Data.Entity.Infrastructure.DbEntityEntry`1.set_State(EntityState value)
at Entities.Classes.Class_tblInvoice.Udf_Edit_Invoice(tblInvoice inv) in E:\Programming\P1\ADVD9\TarkeEtiad\SourceCodeEF\Entities\Classes\Class_tblInvoice.cs:line 77
This: tblInvoice invtPub = new tblInvoice();
[Table("tblInvoice")]
public partial class tblInvoice
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public tblInvoice()
{
tblInvoiceDetail = new HashSet<tblInvoiceDetail>();
}
[Key]
public long InvoiceTitleID { get; set; }
[Required]
public Boolean IsCanceled { get; set; }
[Required]
public int CreatorUserID { get; set; }
[Required]
public long CustomerID { get; set; }
public DateTime DateOfFactor { get; set; }
[Required]
[StringLength(10)]
public string ShamsiDateOfFactor { get; set; }
public decimal? TotalPriceOfFactor { get; set; }
public decimal TaxOfInvoice { get; set; }
public decimal TotalPriceOfFactorWithTax { get; set; }
public decimal PayCashOfInvoice { get; set; } //نقدی
public decimal PayCardOfInvoice { get; set; } //کارتخوان
public decimal PayDebtOfInvoice { get; set; } //بدهی
public decimal PayCredOfInvoice { get; set; } //طلب
[MaxLength(1500)]
public String StrDescription { get; set; }
public virtual tblCustomers tblCustomers { get; set; }
public virtual tblPUsers tblPUsers { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<tblInvoiceDetail> tblInvoiceDetail { get; set; }
}
Don't use any transactions since you only need to add one record.
try this
using (DbContextModel db = new DbContextModel())
{
try
{
var existedInvoice= db.Set<tblInvoice>().FirstOrDefault(i=> i.InvoiceTitleID = inv.InvoiceTitleID );
if (existedInvoice!=null)
{
db.Entry(existedInvoice).CurrentValues.SetValues(inv);
db.SaveChanges();
return 1;
} else return 0;
}
catch(Exception ee)
{
return 0;
}
}

Error CS0161 'RateController.GetRateById(long)': not all code paths return a value

I have an error
Severity Code Description Project File Line Suppression State Error CS0161 'RateController.GetRateById(long)': not all code paths return a value shenoywebapi D:\shenoystudio\shenoywebapi\Controllers\RateController.cs 192 Active
[Route("api/rate/getrate/{id}")]
public Rate GetRateById(long id)
{
var result = new Rate();
var dsRate = SqlHelper.ExecuteDataset(AppDatabaseConnection, CommandType.StoredProcedure, 0, "GetRateById", new SqlParameter("#Id", id));
if (dsRate.Tables[0].Rows.Count > 0)
{
DataRow row = dsRate.Tables[0].Rows[0];
result = new Rate
{
Id = Convert.ToInt64(row[0]),
wefDate = Convert.ToDateTime(row[1]),
//ProductRates =new List<ProductRate>() { new ProductRate() { Rate = Convert.ToInt64(row[2])} }
};
}
var ProductRatesList = new List<ProductRate>();
var dsRateDetails = SqlHelper.ExecuteDataset(AppDatabaseConnection, CommandType.StoredProcedure, 0, "GetRateDetailsById", new SqlParameter("#RateId", id));
if (dsRateDetails.Tables[0].Rows.Count > 0)
{
foreach (DataRow row in dsRateDetails.Tables[0].Rows)
{
ProductRatesList.Add(new ProductRate
{
Rate = Convert.ToDecimal(row[0])
});
}
result.ProductRates = ProductRatesList;
return result;
}
}
This is my rate model
{
public class Rate
{
public long Id { get; set; }
public DateTime wefDate { get; set; }
public IList<ProductRate> ProductRates { get; set; }
}
}
This is my ProductRate Model
namespace shenoywebapi.Models
{
public class ProductRate
{
public long Id { get; set; }
public string SerialNumber { get; set; }
public long ProductId { get; set; }
public string ProductName { get; set; }
public string Unit { get; set; }
public decimal Rate { get; set; }
}
}
Only on this part you have a return statement:
if (dsRateDetails.Tables[0].Rows.Count > 0)
{
foreach (DataRow row in dsRateDetails.Tables[0].Rows)
{
ProductRatesList.Add(new ProductRate
{
Rate = Convert.ToDecimal(row[0])
});
}
result.ProductRates = ProductRatesList;
return result;
}
if the code goes not to this if statement, there is no return statement
if (dsRateDetails.Tables[0].Rows.Count > 0)
you should add this before the last curly brace of the method:
return result;

Azure Mobile Service for Windows Phone 8.1 - Insert to existing DB

I am writing an app that has an Azure database. I've never did nything connected with Azure, so I am new to all the stuff. I've found on the internet and at microsoft documentation some tutorials, but I must have got sth wrong, cause it doesn't work. So I have a table at my database called Week, I've created a model in my code:
[DataContract]
public class Week
{
//[JsonProperty(PropertyName = "Id")]
//[DataMember]
public int Id { get; set; }
[JsonProperty(PropertyName = "Book")]
[DataMember]
public Book CurrentBook { get; set; }
[JsonProperty(PropertyName = "Is_Read")]
[DataMember]
public Boolean IsRead { get; set; }
[JsonProperty(PropertyName = "Pages_Read")]
[DataMember]
public int PagesRead { get; set; }
[JsonProperty(PropertyName = "Start_Date")]
[DataMember]
public DateTime StartDate { get; set; }
[JsonProperty(PropertyName = "User")]
[DataMember]
public User Reader { get; set; }
[JsonProperty(PropertyName = "Week_Number")]
[DataMember]
public int WeekNumber { get; set; }
public Week(Book currentBook, Boolean isRead, int pagesRead, DateTime startDate, User reader, int weekNumber)
{
CurrentBook = currentBook;
IsRead = isRead;
PagesRead = pagesRead;
StartDate = startDate;
Reader = reader;
WeekNumber = weekNumber;
}
public Week()
{
}
public int GetMonth()
{
//TODO: Implement the method.
return 0;
}
}
Then I created the WeekRepository for CRUD operations:
public class WeekRepository : BaseRepository<Week>
{
private IMobileServiceTable<Week> weekTable;
public string errorMesage = string.Empty;
public WeekRepository()
{
weekTable = MobileService.GetTable<Week>();
}
public async override Task<int> Save(Week entity)
{
try
{
await weekTable.InsertAsync(entity);
// .ContinueWith(t =>
//{
// if (t.IsFaulted)
// {
// errorMesage = "Insert failed";
// }
// else
// {
// errorMesage = "Inserted a new item with id " + entity.Id;
// }
//});
}
catch (WebException ex)
{
errorMesage = ex.Message;
}
return entity.Id;
}
public override void Update(Week entity)
{
return;
}
public override Week Load(int bookId)
{
var week = weekTable.Where(w => w.IsRead == false).ToListAsync();
return week.Result.Single();
}
public override List<Week> LoadByUserId(int userId)
{
return new List<Week>();
}
public Week LoadCurrentWeek(int userId)
{
return new Week();
}
}
To test if it works, I wrote a simple test:
[TestMethod]
public void ShouldSaveWeekToTheDB()
{
//ARANGE
Week weekTestEntity = new Week(null, false, 10, new DateTime(), null, 1);
//ACT
int id = weekRepository.Save(weekTestEntity).Result;
//ASSERT
var savedItem = weekRepository.Load(1);
Assert.AreEqual(false, savedItem.IsRead);
}
However, InsertAsync() throws an exception - Not Found. I've no idea what I am doing wrong, cause it seems a simple thing as far as I can see from the material on the Internet.
If You could help me, I would be really grateful!
Thank You in advance!
Best Regards,
Roman.

How can i get the time ( only hours)

I need to show the number of hours in a Grid, how ever when I use a method to get all of the columns, the results show the Date.
This is my scenario.
(My Entities)
public class Turno
{
public int Cod_Turno { get; set; }
public string Des_Turno { get; set; }
public string Des_NombreCorto { get; set; }
public DateTime Hor_Inicio { get; set; }
public DateTime Hor_Fin { get; set; }
public bool Flag_Activo { get; set; }
}
This is my Access Layer
public IList<Turno> Listar()
{
var turnos = new List<Turno>();
var comando = _baseDatos.GetStoredProcCommand("HOR_Listar_Turno");
using (var lector = _baseDatos.ExecuteReader(comando))
{
while (lector.Read())
{
turnos.Add(new Turno
{
Cod_Turno = lector.GetInt32(lector.GetOrdinal("Cod_Turno")),
Des_Turno = lector.GetString(lector.GetOrdinal("Des_Turno")),
Des_NombreCorto = lector.GetString(lector.GetOrdinal("Des_NombreCorto")),
Hor_Inicio = new DateTime(lector.IsDBNull(lector.GetOrdinal("Hor_Inicio")) ? 0 : lector.GetOrdinal("Hor_Inicio")),
Hor_Fin = new DateTime(lector.IsDBNull(lector.GetOrdinal("Hor_Fin")) ? 0 : lector.GetOrdinal("Hor_Fin")),
Flag_Activo = lector.GetBoolean(lector.GetOrdinal("Flag_Activo"))
});
}
}
comando.Dispose();
return turnos;
}
Is there a way to get a Time in the Line to get HOR_Inicio and HOR_Fin; I only need the hours and minutes.
If you want the hours and minutes as a string you could use DateTime.Now.ToString("HH:mm");

entity framework saves first item in the loop but none other

In my controller I'm looping through items and saving them to my db. The problem is that it saves the first item, but none of the others. I put a breakpoint on the "SaveItem()" line in the loop and it hits it every time, but what seems odd to me is that it only goes through to the method for the 1st item.
What am I doing wrong?
public void SubmitItem(Cart cart, ShippingDetails shippingDetails, ProcessedItems processedItem, string orderID)
{
var cartItems = cart.Lines;
//CartIndexViewModel cartIndex = new CartIndexViewModel();
//var customID = cartIndex.OrderID;
foreach(var item in cartItems)
{
processedItem.OrderID = orderID;
processedItem.ProductID = item.Product.ProductID;
processedItem.Name = item.Product.Name;
processedItem.Description = item.Product.Description;
processedItem.Price = item.Product.Price;
processedItem.Category = item.Product.Category;
processedItem.ImageName = item.Product.ImageName;
processedItem.Image2Name = item.Product.Image2Name;
processedItem.Image3Name = item.Product.Image3Name;
processedItem.BuyerName = shippingDetails.Name;
processedItem.Line1 = shippingDetails.Line1;
processedItem.Line2 = shippingDetails.Line2;
processedItem.Line3 = shippingDetails.Line3;
processedItem.City = shippingDetails.City;
processedItem.State = shippingDetails.State;
processedItem.Zip = shippingDetails.Zip;
processedItem.Country = shippingDetails.Country;
processedItem.Status = "Submitted";
processedItems.SaveItem(processedItem);
}
}
public class EFProcessedItemsRepository : IProcessedItems
{
private EFDbContext context = new EFDbContext();
public IQueryable<ProcessedItems> ProcessedItem
{
get { return context.ProcessedItems; }
}
public void SaveItem(ProcessedItems processedItem)
{
if(processedItem.ProcessedID == 0)
{
try
{
context.ProcessedItems.Add(processedItem);
context.SaveChanges();
}
catch (Exception)
{
throw;
}
}
else
{
context.Entry(processedItem).State = EntityState.Modified;
}
}
public void DeleteItem(ProcessedItems processedItem)
{
context.ProcessedItems.Remove(processedItem);
context.SaveChanges();
}
}
here is the class for the processedItem:
public class ProcessedItems
{
[Key]
public int ProcessedID { get; set; }
public string OrderID { get; set; }
public int ProductID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public string Category { get; set; }
public string ImageName { get; set; }
public string Image2Name { get; set; }
public string Image3Name { get; set; }
public string Status { get; set; }
//shipping
public string BuyerName { get; set; }
public string Line1 { get; set; }
public string Line2 { get; set; }
public string Line3 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public string Country { get; set; }
}
Interface:
public interface IProcessedItems
{
IQueryable<ProcessedItems> ProcessedItem { get; }
void SaveItem(ProcessedItems processedItem);
void DeleteItem(ProcessedItems processedItem);
}
try calling context.SaveChanges() after adding all of the items, I think it should persist them all in one go.
Another thing to try:
Refactor your code so that SaveItem accepts only one item to save, Add it and call SaveChanges()
Loop through the cart items outside the method and call the method with one item to save at a time.
// set orderID, shippingDetails above
foreach(var item in cartItems)
{
ProcessedItems processedItem = new ProcessedItems();
processedItem.OrderID = orderID;
processedItem.ProductID = item.Product.ProductID;
processedItem.Name = item.Product.Name;
processedItem.Description = item.Product.Description;
processedItem.Price = item.Product.Price;
processedItem.Category = item.Product.Category;
processedItem.ImageName = item.Product.ImageName;
processedItem.Image2Name = item.Product.Image2Name;
processedItem.Image3Name = item.Product.Image3Name;
processedItem.BuyerName = shippingDetails.Name;
processedItem.Line1 = shippingDetails.Line1;
processedItem.Line2 = shippingDetails.Line2;
processedItem.Line3 = shippingDetails.Line3;
processedItem.City = shippingDetails.City;
processedItem.State = shippingDetails.State;
processedItem.Zip = shippingDetails.Zip;
processedItem.Country = shippingDetails.Country;
SubmitItem(processedItem);
}
public void SubmitItem(ProcessedItems processedItem)
{
processedItem.Status = "Submitted";
processedItems.SaveItem(processedItem);
}
I think it is because processedItem is the same instance for each loop iteration. So after it has been through SaveItem once, it has its ProcessedID set and therefore won't get processed again.
My first guess is that you always store one entity, which is stored in processedItem, which is a input parameter. Try to create new Entity on each loop and then save it. In other words, you assign values to input parameter
processedItem.OrderID = orderID;
and then store same entity each time, but with changed fields
processedItems.SaveItem(processedItem);

Categories

Resources