When I input the data on the form I get an error saying "when converting a string to datetime, parse the string to take the date before putting each variable into the DateTime object". I tried changing the string format and hardcoded the viewModel.Date, viewModel.Time but I still get an error when can anyone suggest an way of overcoming this?
public ActionResult Create(GigFormViewModel viewModel)
{
var artistId = User.Identity.GetUserId();
var artist = _context.Users.Single(u => u.Id == artistId);
var genre = _context.Genres.Single(g => g.Id == viewModel.Genre);
var gig = new Gig
{
Àrtist = artist,
DateTime = DateTime.Parse(string.Format("{0}{1}", viewModel.Date, viewModel.Time)),
Genre = genre,
Venue = viewModel.Venue
};
_context.Gigs.Add(gig);
_context.SaveChanges();
return RedirectToAction("Index", "Home");
}
public class Gig
{
public int Id { get; set; }
[Required]
public ApplicationUser Àrtist { get; set; }
public DateTime DateTime { get; set; }
[Required]
[StringLength(255)]
public string Venue { get; set; }
[Required]
public Genre Genre { get; set; }
}
public class GigFormViewModel
{
public string Venue { get; set; }
public string Date { get; set; }
public string Time { get; set; }
public int Genre { get; set; }
public IEnumerable<Genre> Genres { get; set; }
}
The problem is here:
DateTime = DateTime.Parse(string.Format("{0}{1}", viewModel.Date, viewModel.Time)),
you should put "space" between {0} and {1}:
DateTime = DateTime.Parse(string.Format("{0} {1}", viewModel.Date, viewModel.Time)),
Related
My code returns userid, categoryid, locationid instead of the names to my list view.
I want to return names instead of id
//This is the get method in the service
public async Task<IEnumerable<JobViewModel>> GetAllJobsAsync()
{
var jobs = _appDbContext.Jobs
.Include(j => j.Category)
.Include(j => j.Location)
.Include(j => j.User)
.ToList();
return jobs.Select(job => new JobViewModel(job));
}
//Get method in the controller
public async Task<IActionResult> ListOfJobs()
{
var list = await _jobService.GetAllJobsAsync();
return Ok(list);
}
//This is the JobViewModel
public JobViewModel(JobClass job)
{
JobId = job.JobId;
JobTitle = job.JobTitle;
Description = job.Description;
Requirement = job.Requirement;
Experience = job.Experience;
Salary = job.Salary;
DatePosted = job.DatePosted;
Deadline = job.Deadline;
UserId = job.Id;
CategoryId = job.CategoryId;
LocationId = job.LocationId;
}
public Guid JobId { get; set; }
public string JobTitle { get; set; }
public string Description { get; set; }
public string Requirement { get; set; }
public string Experience { get; set; }
public int Salary { get; set; }
public DateTime DatePosted { get; set; }
public DateTime Deadline { get; set; }
public Guid UserId { get; set; }
public int LocationId { get; set; }
public int CategoryId { get; set; }
public IEnumerable<CategoryViewModel> Categories { get; set; }
public IEnumerable<LocationViewModel> Locations { get; set; }
}
I have a multi-digit category table and I want to query the bottom category from that table.
This way I can get the first digit when I query, but it does not bring the lower digits
var query = Query<Category>.ElemMatch(x => x.SubCategories, builder => builder.EQ(actor => actor.IntegrationCategoryCode, categoryId));
var repository = new Data.MongoDB.Repository.MongoRepository<Category>();
var result= repository.CustomQuery(query).ToList();
[CollectionName("Category ")]
public class Category : Base.Entity
{
[BsonElement("CategoryId")]
public int CategoryId { get; set; }
[BsonElement("IntegrationCategoryName")]
public string IntegrationCategoryName { get; set; }
[BsonElement("IntegrationCategoryCode")]
public string IntegrationCategoryCode { get; set; }
[BsonElement("IntegrationParentCode")]
public string IntegrationParentCode { get; set; }
[BsonElement("Deleted")]
[BsonRepresentation(BsonType.Boolean)]
public bool Deleted { get; set; }
[BsonElement("CreateDate")]
[BsonDateTimeOptions(Kind = DateTimeKind.Utc)]
public DateTime CreateDate { get; set; }
[BsonElement("UpdateDate")]
[BsonDateTimeOptions(Kind = DateTimeKind.Utc)]
public DateTime UpdateDate { get; set; }
public List<Category> SubCategories { get; set; }
}
How to calculate account receivable using LINQ.
I have tried this but stuck here.
I have done this in SQL but I want this in LINQ so I can use it in my MVC project.
var sale = saleslist.GroupBy(s => s.BuyerId).Select(s => s.Sum(u => u.Amount)).ToList();
var receipt = receiptslist.GroupBy(r => r.StakeHolderId).Select(t => t.Sum(u => u.Amount)).ToList();
List<AccountReceivablesVM> res = db.StakeHolders
.Where(r=>r.StakeHolderTypeId == "0b85a69e-55f2-4142-a49d-98e22aa7ca10")
.Select(rvm => new AccountReceivablesVM
{
CompanyName = rvm.CompanyName,
Receivables = //don't know what to do here
}).ToList();
Models:
public class StakeHolder
{
public string StakeHolderId { get; set; }
public string CompanyName { get; set; }
public string Address { get; set; }
public string Contact { get; set; }
public string StakeHolderTypeId { get; set; }
}
public class Sale
{
public string SaleId { get; set; }
public string RefNo { get; set; }
public DateTime Date { get; set; }
public string BuyerId { get; set; }
public string Description { get; set; }
public Nullable<double> Amount { get; set; }
}
public class PaymentsAndReceipt
{
public string PaymentAndReceiptId { get; set; }
public Nullable<int> VoucherNo { get; set; }
public DateTime Date { get; set; }
public string StakeHolderId { get; set; }
public string Description { get; set; }
public Nullable<double> Amount { get; set; }
}
public class AccountReceivablesVM
{
public string CompanyName { get; set; }
public Nullable<double> Receivables { get; set; }
}
Expected Result:
You can join first with stakeholderId and then sum the amount and then group by with company name and stakeholder id, however I write the code in Linq. I have considered the stakeholderid as the primary key of your table just because you have not mentioned the schema of stakeholder so.
var result = from s in db.StakeHolders
join pr in db.PaymentsAndReceipt on s.StakeHolderId equals pr.StakeHolderId
where StakeHolderTypeId == "0b85a69e-55f2-4142-a49d-98e22aa7ca10"
group s by new { s.StakeHolderId,s.CompanyName} into p
select new
{
StakeHolderId= p.Key.StakeHolderId,
CompanyName= p.Key.CompanyName,
Receivables = string.Format("{0:C}", p.Sum(y => y.Amount))
};
I'm trying to update a many-to-many relationship. I have two models, diary and tags. The model diary contains a list of tags and tags contains a list of diaries. But whenever I try to add another tag to an existing list or change an existing one I get thrown an exception:
The entity type List`1 is not part of the model for the current context.
Does my way of updating even work on collections? Or is there another approach I should be looking at?
Diary Model
public class Diary
{
[Key]
public int IdDiary { get; set; }
[Required(ErrorMessage = "This field is required")]
public string NameDiary { get; set; }
[Required(ErrorMessage = "This field is required")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime CreationDate { get; set; }
public bool Locked { get; set; }
public ICollection<Entry> Entries { get; set; }
[DataType(DataType.MultilineText)]
[Required(ErrorMessage = "This field is required")]
public string Summary { get; set; }
public string ImageUrl { get; set; }
public ICollection<Tag> Tags { get; set; }
}
Entry Model
public class Entry
{
[Key]
public int IdEntry { get; set; }
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime CreationDate { get; set; }
[DataType(DataType.MultilineText)]
public string EntryText { get; set; }
[ForeignKey("Diary_IdDiary")]
public Diary Diary { get; set; }
public int Diary_IdDiary { get; set; }
public string EntryName { get; set; }
}
Tag Model
public class Tag
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Diary> Diaries { get; set; }
}
Update Method
public void UpdateDiary(Diary updatedDiary)
{
var searchResult = SearchDiary(updatedDiary);
if (searchResult != null)
{
updatedDiary.IdDiary = searchResult.IdDiary;
_context.Entry(searchResult).CurrentValues.SetValues(updatedDiary);
_context.Entry(searchResult.Tags).CurrentValues.SetValues(updatedDiary.Tags);
_context.SaveChanges();
}
}
SearchDiary Method
public Diary SearchDiary(Diary searchDiary)
{
var queryResult =
_context.Diaries.Include(d => d.Entries).Include(d => d.Tags)
.Where(d => (d.NameDiary == searchDiary.NameDiary && d.CreationDate == searchDiary.CreationDate) || d.IdDiary == searchDiary.IdDiary);
return queryResult.FirstOrDefault();
}
Thank you for reading
Here is one way:
DiaryModel
public class Diary
{
[Key]
public int IdDiary { get; set; }
[Required(ErrorMessage = "This field is required")]
public string NameDiary { get; set; }
[Required(ErrorMessage = "This field is required")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime CreationDate { get; set; }
public bool Locked { get; set; }
public virtual ICollection<Entry> Entries { get; set; }
[DataType(DataType.MultilineText)]
[Required(ErrorMessage = "This field is required")]
public string Summary { get; set; }
public string ImageUrl { get; set; }
public ICollection<Tag> Tags { get; set; }
}
EntryModel
public class Entry
{
[Key]
public int IdEntry { get; set; }
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime CreationDate { get; set; }
[DataType(DataType.MultilineText)]
public string EntryText { get; set; }
[ForeignKey("Diary_IdDiary")]
public virtual Diary Diary { get; set; }
public int Diary_IdDiary { get; set; }
public string EntryName { get; set; }
}
For Search
public Diary SearchDiary(int DiaryId)
{
return _context.Diaries
.Include(p => p.Entries)
.Include(p => p.Tags)
.FirstOrDefault(p => p.IdDiary == DiaryId);
}
For Update
public void UpdateDiary(Diary Diary)
{
_context.Update(Diary);
_context.SaveChanges();
}
You should pass the modified Diary object to the update functions.
How do I iterate through a list which is returning a DateTime List and pass individual dates into a function which is expecting a DateTime parameter ?
Below is my LINQ query that returns List of Dates:
var lastModifiedDates = context.Reviews
.Where(s => s.IsActive == true)
.Where(s => s.ReviewStatusId == (int)ReviewStatuses.EmployeeSignature)
.Select(v => v.ModifiedDate)
.ToList();
Here is how I am trying to pass dates:
foreach (var lastModifiedDate in lastModifiedDates)
{
AddBusinessDay(lastModifiedDate, 15);
}
Here is how AddBusinessDay function looks like:
public static DateTime AddBusinessDay (DateTime date, int days)
On AddBusinessDay(lastModifiedDate, 15); I get the following error:
Error 28 The best overloaded method match for 'EvaluationFormAccess.AddBusinessDay(System.DateTime, int)' has some invalid arguments
Review entity:
public int ReviewId { get; set; }
public System.Guid ReviewGuid { get; set; }
public int ReviewStatusId { get; set; }
public int PersonId { get; set; }
public int SupervisorId { get; set; }
public int ReviewYearId { get; set; }
public Nullable<bool> EmployeeOnLeave { get; set; }
public Nullable<bool> PlanInPlace { get; set; }
public string EmployeeComments { get; set; }
public string EmployeeSignature { get; set; }
public Nullable<System.DateTime> EmployeeSignDate { get; set; }
public string ManagerComments { get; set; }
public string ManagerSignature { get; set; }
public Nullable<System.DateTime> ManagerSignDate { get; set; }
public System.DateTime CreatedDate { get; set; }
public System.Guid CreatedBy { get; set; }
public Nullable<System.DateTime> ModifiedDate { get; set; }
public Nullable<System.Guid> ModifiedBy { get; set; }
public bool IsActive { get; set; }
Your ModifiedDate property is actually a Nullable<DateTime> (also can be written as DateTime?), which is actually not at all a DateTime.
You have two options:
Resolve the possible DateTime into an actual DateTime in your LINQ query:
var lastModifiedDates = context.Reviews
.Where(s => s.IsActive == true)
.Where(s => s.ReviewStatusId == (int)ReviewStatuses.EmployeeSignature)
.Where(v => v.ModifiedDate.HasValue)
.Select(v => v.ModifiedDate.Value)
.ToList();
Or do it in your loop:
foreach (var lastModifiedDate in lastModifiedDates)
{
if (lastModifiedDate.HasValue)
AddBusinessDay(lastModifiedDate.Value, 15);
}
Loop solution courtesy of Ksv3n