I have a question , I have a Timespan in my Database and i want to use it in my controller but this error appears
Cannot implicitly convert type 'string' to 'System.TimeSpan'
Controller :
int id = Convert.ToInt32(clientId);
clientShift = (from a in db.Client_Shift
where a.ID == id
select a).SingleOrDefault();
clientShift.DayFrom_LookID = Convert.ToInt32(dateFrom);
clientShift.DayTo_LookID = Convert.ToInt32(dateTo);
This is where the error occur --> clientShift.EndTime = endTime.Trim();
clientShift.DateModified = DateTime.UtcNow;
clientShift.ModifiedBy = User.Identity.Name;
Model :
public partial class Client_Shift
{
public int ID { get; set; }
public int Client_ID { get; set; }
public int DayFrom_LookID { get; set; }
public int DayTo_LookID { get; set; }
public System.TimeSpan StartTime { get; set; }
public System.TimeSpan EndTime { get; set; }
Thanks for someone who can help me :D
You need to Parse the TimeSpan:
clientShift.EndTime = TimeSpan.Parse(endTime.Trim());
If the string does not represent a valid time span, you will get an exception.
Related
I am converting an existing application and I am using the existing database structure.
This is the model of the data I am querying:
public partial class StaffNotes
{
public int RecordNumber { get; set; }
public double? ContactNumber { get; set; }
public double? WriteNumber { get; set; }
public double? ToStaff { get; set; }
public double? FromStaff { get; set; }
public string Note { get; set; }
public DateTime? CriticalDate { get; set; }
public DateTime? NoteDate { get; set; }
public int? TicketNumber { get; set; }
public bool Imp { get; set; }
}
Instead of displaying the number of the ToStaff, I would like to display the appropriate name.
I have written the following query:
var staffNotes = _context.StaffNotes.FromSql("Select s.record_number, s.contact_number, s.To_Staff, s.From_Staff, s.Note_Date, s.Ticket_Number, s.Imp, s.Critical_Date, S.Note, s.write_number, c.first_name, c.last_name from staffnotes s, contacts c where s.contact_number = c.contact_number and s.Contact_Number = " + id).ToList();
My code runs and I'm not getting any errors. The only issue is the first_name and last_name do not appear in the data.
Is this because it is not part of the model? Is there a way to get around this?
I added the missing properties and it is now working.
you must use FromSqlRaw with using Microsoft.EntityFrameworkCore; instead of FromSql
var staffNotes = _context.StaffNotes.FromSqlRaw("Select s.record_number, s.contact_number, s.To_Staff, s.From_Staff, s.Note_Date, s.Ticket_Number, s.Imp, s.Critical_Date, S.Note, s.write_number, c.first_name, c.last_name from staffnotes s, contacts c where s.contact_number = c.contact_number and s.Contact_Number = " + id).ToList();
I want to pass a value from the model...
#Html.HiddenFor(model => model.ProductId)
Exception thrown: 'System.ArgumentException' in System.Web.Mvc.dll
Additional information: Value cannot be null or empty.
But it is throwing this exception and I don't know why... And no ProductId isn't null.
Action
[HttpGet]
public ActionResult Edit(int ProductId = 0)
{
PCsViewModel pcViewModel = new PCsViewModel();
ProductRepository productRepo = new ProductRepository();
Product dbProduct = productRepo.GetAll(item=>item.ID==ProductId);
PCsRepository pcsRepo = new PCsRepository();
PC dbPC = pcsRepo.GetAll(item=>item.ProductID==ProductId);
if (dbProduct != null && dbPC != null)
{
pcViewModel = new PCsViewModel(dbProduct,dbPC);
}
return View(pcViewModel);
}
ViewModel
public int ProductId { get; set; }
[Required]
public string Name { get; set; }
public string PCsInfo { get; set; }//for the front view
[Required]
public double Price { get; set; }
[Required]
public string ImagePath { get; set; }
[Required]
public string Processor { get; set; }
[Required]
public string OS { get; set; }
[Required]
public int RAM { get; set; }
[Required]
public int Storage { get; set; }
[Required]
public string VideoCard { get; set; }
[Required]
public int CategoryID { get; set; }
public PCsViewModel()
{
}
public PCsViewModel(Product product, PC pc)
{
this.ProductId = product.ID;
this.CategoryID = product.CategoryID;
this.OS = product.OS;
this.Processor = product.Processor;
this.Name = product.Name;
this.RAM = product.RAM;
this.Storage = product.Storage;
this.VideoCard = pc.VideoCard;
this.PCsInfo = "PC "+product.Name + "with processor " + product.Processor;
this.Price = (double)product.Price;
this.ImagePath = Path.Combine(Constants.ImagesPCsDirectory, product.ImageName);
}
Based of the discussion in the comments, it looks like your actual issue wasn't related to the ProductId property but instead your ImagePath property, which was being passed into a Url.Content() helper (to resolve the appropriate path).
This would work as expected if the path existed, but if that property was null or empty, you would receive the ArgumentNullException that you currently are. The best approach would likely be to just only render the specific path if that specific property wasn't null:
#if (!string.IsNullOrEmpty(Model.ImagePath)) {
// Use Url.Content(Model.ImagePath) within here safely
}
There are multiple different ways to handle this, such as adding an additional property on your model to clean things up:
public bool HasImage => !string.IsNullOrEmpty(ImagePath);
And then use:
#if (Model.HasImage) {
// Use Url.Content(Model.ImagePath) within here safely
}
What i have initially on my App is a list of expensives that is created based on the Scarfolding System but that list is the same for each User, and what i want is that each user can create his own list of expensives and see his own data.
So in the expensive class i did this:
public class Despesa
{
public int TipoDespesaId { get; set; }
public int DespesaId { get; set; }
public string UserId { get; set; }
[Display(Name = "Descrição da Despesa")]
[Required]
public string DespesaDescricao { get; set; }
[Display(Name = "Valor")]
[Required]
public decimal DespesaValor { get; set; }
public int TipoPagamentoId { get; set; }
[Display(Name = "Data")]
[DataType(DataType.Date)]
[CustomValidation(typeof(Validator), "ValidateEndTimeRange")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}",ApplyFormatInEditMode = true)]
[Required]
public DateTime Data { get; set; }
public TipoDespesa TipoDespesa { get; set; }
public TipoPagamento TipoPagamento { get; set; }
[Display(Name = "Comentário")]
public string Comentario { get; set; }
}
i just passed the UserId to the model and then in the Index controller of my Expensive View i did a linq query to compare the currentUserID to the Id of the expensive User here is my code:
public ActionResult Index()
{
String userId = User.Identity.GetUserId();
var despesas = from r in db.Despesas.Include(d => d.TipoDespesa).Include(d => d.TipoPagamento).Include(d => d.UserId)
where r.UserId.Equals(userId)
select r;
return View(despesas.ToList());
}
what i need to know is what i am doing wrong cause i get a invalidOperationException
Only navigation properties can be used with .Include() it seems.
You are trying to include a primitive property (UserId), and it then throws the error when converting to a list because it has no navigation property.
var despesas = from r in db.Despesas.Include(d => d.TipoDespesa).Include(d => d.TipoPagamento).Where(x => x.UserId == userId) select r;
I am trying to get a query that returns everything properly formatted for my ViewModel so I do not have to manually copy everything over from my entity models. I have this Linq query that is giving me an error. :
var query = from i in context.Invoices
join l in context.LineItems on i.InvoiceID equals l.InvoiceID into il
where i.InvoiceID == id
select new InvoiceViewModel()
{
InvoiceID = i.InvoiceID,
CustomerID = i.CustomerID,
InvoiceNote = i.Note,
InvoiceDate = i.InvoiceDate,
Terms = i.Terms,
LineItems = il.ToList<LineItemViewModel>()
};
This is my ViewModel
public class InvoiceViewModel {
public int InvoiceID { get; set; }
public int CustomerID { get; set; }
public string InvoiceNote { get; set; }
public DateTime InvoiceDate { get; set; }
public string Terms { get; set; }
public virtual ICollection<LineItemViewModel> LineItems { get; set; }
}
public class LineItemViewModel {
public int LineItemID { get; set; }
public int InvoiceID { get; set; }
public int Quantity { get; set; }
public string Item { get; set; }
public decimal Amount { get; set; }
public string LineItemNote { get; set; }
}
The error I am getting is (the red squigly is under the il in LineItems = il.ToList())
'IEnumerable<LineItem>' does not contain a definition for 'ToList' and the best extension method overload 'Enumerable.ToList<LineItemViewModel>(IEnumerable<LineItemViewModel>)' requires a receiver of type 'IEnumerable<LineItemViewModel>'
Which I (sorta, kinda, a little) understand. So what is the proper syntax for this?
You need to explicitly initialize your LineItemViewModel instances from the LineItem entities. You might be better off writing this as a correlated subquery rather than a join:
var query =
from i in context.Invoices
where i.InvoiceID == id
select new InvoiceViewModel()
{
InvoiceID = i.InvoiceID,
CustomerID = i.CustomerID,
InvoiceNote = i.Note,
InvoiceDate = i.InvoiceDate,
Terms = i.Terms,
LineItems =
(
from li in context.LineItems
where li.InvoiceID == i.InvoiceID
select new LineItemViewModel
{
LineItemID = li.LineItemID,
InvoiceID = li.InvoiceID,
Quantity = li.Quantity,
Item = li.Item,
Amount = li.Amount,
LineItemNote = li.LineItemNote,
}
).ToList()
};
I am testing my controller code using IOC Unity. The issue is with the initialisation of the model that I am passing to constructor of my controller.
Here is my code in the test project
[TestMethod]
public void TestHomeControllerIndexMethod()
{
HomeController controller = new HomeController(new stubPeopleService());
ViewResult result = controller.Index() as ViewResult;
Assert.AreEqual(0, result);
}
Below is the code of the stubPeopleService that I have created which I pass to my controller constructor above
public class stubPeopleService : IPeople
{
public int Age
{
get;
set;
}
public string BirthPlace
{
get;
set;
}
public DateTime DateOfBirth
{
get;
set;
}
public int GetAge(DateTime reference, DateTime birthday)
{
int age = reference.Year - birthday.Year;
if (reference < birthday.AddYears(age)) age--;
return age + 1;
}
public int Height
{
get;
set;
}
public List<People> listPeople { get { return GetPeople(); } }
public string Name
{
get;
set;
}
public int Weight
{
get;
set;
}
private List<People> GetPeople()
{
List<People> list = new List<People>();
list.Add(new People
{
Name = "Ranjit Menon",
DateOfBirth = DateTime.Today,
BirthPlace = "London",
Age = 25,
Height = 175,
Weight = 85
});
return list.OrderBy(x => x.Name).ToList();
}
}
When I debug my test , I notice that the all the properties do not contain any value. The only property that contains value is listPeople property. The listpeople property does initialise the other properties but throws an object cannot be created error.Let me know if I am doing the test correctly. I need to do a test initialising the model with some values.
Code from my home controller
private IPeople peopleService;
public HomeController(IPeople people)
{
this.peopleService = people;
}
public ActionResult Index()
{
return View(peopleService);
}
Please find the IPeople interface below
public interface IPeople
{
int Age { get; set; }
string BirthPlace { get; set; }
DateTime DateOfBirth { get; set; }
int GetAge(DateTime reference, DateTime birthday);
int Height { get; set; }
List<People> listPeople { get; }
string Name { get; set; }
int Weight { get; set; }
}