Error:The specified cast from a materialized 'System.TimeSpan' type to the 'System.DateTime' type is not valid - entity-framework

I am doing my application in MVC. I am using stored procedure to list some
values. I calling that procedure in my controller.
My Procedure is
ALTER procedure [dbo].[spGetWaitingList]
#BusinessUserId int
As
Begin
SELECT WorkHour.WorkHourId, WorkHour.EndTime, WorkHour.Description, tblApp.EndDate
FROM WorkHour INNER JOIN
tblApp ON WorkHour.BusinessUserId = tblApp.UserId2 and WorkHour.EndTime < Cast (tblApp.EndDate as Time)
End
My controllercode is
var parameters = new SqlParameter[1];
parameters[0] = new SqlParameter { ParameterName = "BusinessUserId", Value = id };
List<Appt> wt = new List<Appt>();
using (SYTEntities context = new SYTEntities())
{
wt = context.Database.SqlQuery<Appt>("exec spGetWaitingList #BusinessUserId", parameters).ToList();
}
My model Appt is
public class Appt
{
public int BusinessID { get; set; }
public string FirstName { get; set; }
public string BusinessName { get; set; }
public string BusinessCategory { get; set; }
public int UserID { get; set; }
public int UserTypeID { get; set; }
public int Id { get; set; }
public TimeSpan StartTime { get; set; }
public TimeSpan EndTime { get; set; }
public string AddCustomer { get; set; }
public string EndDate { get; set; }
public DateTime HolidayDate { get; set; }
public string HolidayDesc { get; set; }
}
In Database I specified the end time as datatype TIME
While running the application am getting an error like this
Can anyone please help me to solve this?
Thanks in advance.

Related

Entity Framework .Core treating foreign key as a primary key

I have the two classes shown below. When trying to insert two HeroEntry with the same IdentityId, the context is only saving one of the two entries. Any ideas what I am doing wrong?
public class Identity
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int IdentityId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
[JsonIgnore]
public virtual HeroEntry HeroEntry { get; set; }
}
public class HeroEntry
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int HeroEntryId { get; set; }
public int IdentityId { get; set; }
public SuperHeroEnum HeroType { get; set; }
public DateTime Startdate { get; set; }
public DateTime EndDate { get; set; }
[ForeignKey("IdentityId")]
public virtual Identity Identity { get; set; }
public virtual List<SuperHeroBreak> SuperHeroBreaks { get; set; }
}
Add code:
var b = new HeroEntry()
{
HeroType = SuperHeroEnum.BATMAN,
Startdate = DateTime.Parse("12/24/2018"),
EndDate = DateTime.Parse("01/04/2019"),
IdentityId = 1,
};
var r = new HeroEntry()
{
HeroType = SuperHeroEnum.ROBIN,
Startdate = DateTime.Parse("12/24/2018"),
EndDate = DateTime.Parse("01/04/2019"),
IdentityId = 1,
};
context.SuperHeroes.AddRange(b, r);
var affected = context.SaveChanges();
Cristian was correct. Adding the navigation property to the identity class solved my issue. Thank you for the help!

How to create Model based C# List from Database

I have Models created through Entity Framework as:
public partial class Order
{
public Order()
{
this.OrderDetails = new HashSet<OrderDetail>();
}
public int OrderID { get; set; }
public string OrderNo { get; set; }
public System.DateTime OrderDate { get; set; }
public string Description { get; set; }
public virtual ICollection<OrderDetail> OrderDetails { get; set; }
}
Then another Details Table:
public partial class OrderDetail
{
public int OrderItemsID { get; set; }
public int OrderID { get; set; }
public string ItemName { get; set; }
public int Quantity { get; set; }
public decimal Rate { get; set; }
public decimal TotalAmount { get; set; }
public virtual Order Order { get; set; }
}
To See the Master Detail Data I made MasterDetails model As:
public class OrderVM
{
public string OrderNo { get; set; }
public DateTime OrderDate { get; set; }
public string Description { get; set; }
public List<OrderDetail> OrderDetails {get;set;}
}
I'm trying to make a method that return a LIST with Join query results but
I'm receiving #Anonymous type error here is my Code:
public static List<OrderVM > mylist()
{
List<OrderVM> slist = new List<OrderVM>();
using (MyDatabaseEntities1 dc = new MyDatabaseEntities1())
{
var myvalues = from O in dc.Orders
join D in dc.OrderDetails
on
O.OrderID equals D.OrderID
select new
{
O.OrderID,
O.OrderDate,
D.Quantity,
D.Rate
};
foreach(var myorders in myvalues)
{
slist.Add(myorders);
}
return slist;
}
}
I need a help that how I can I create a generic list with database fields
Create new class:
public class OrderDetailsModel
{
public int OrderId { get; set; }
public DateTime OrderDate { get; set; }
public int Quantity { get; set; }
public decimal Rate { get; set; }
}
and return list of objects of this class from your method:
using (MyDatabaseEntities1 dc = new MyDatabaseEntities1())
{
var myvalues = from O in dc.Orders
join D in dc.OrderDetails
on
O.OrderID equals D.OrderID
select new OrderDetailsModel
{
OrderId = O.OrderID,
OrderDate = O.OrderDate,
Quantity = D.Quantity,
Rate = D.Rate
};
return myvalues.ToList();
}

The property 'Id' is part of the object's key information and cannot be modified after the second insert

I have a table with Id as primary key
The model generated by EF is this
public partial class Home_Orchard_Users_UserPartRecord
{
public int Id { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public string NormalizedUserName { get; set; }
public string Password { get; set; }
public string PasswordFormat { get; set; }
public string HashAlgorithm { get; set; }
public string PasswordSalt { get; set; }
public string RegistrationStatus { get; set; }
public string EmailStatus { get; set; }
public string EmailChallengeToken { get; set; }
public Nullable<System.DateTime> CreatedUtc { get; set; }
public Nullable<System.DateTime> LastLoginUtc { get; set; }
public Nullable<System.DateTime> LastLogoutUtc { get; set; }
}
When I tried to insert a data from a list, the first insert was okay but the second one I got error: The property 'Id' is part of the object's key information and cannot be modified.
foreach (var ContentItem in ListContentItem)
{
ContentItemData.Data = ContentItem.Data;
ContentItemData.ContentType_id = 3;
Context.Home_Orchard_Framework_ContentItemRecord.Add(ContentItemData);
Context.SaveChanges();
int Return_Id = ContentItemData.Id;
UserData.Id = Return_Id;
UserData.UserName = ContentItem.UserName;
UserData.Email = ContentItem.Email;
UserData.NormalizedUserName = ContentItem.NormalizedUserName;
UserData.Password = "AMQ6a4CzqeyLbWqrd7EwoaTV23fopf++3FpcBlV+Gsvgja3Ye3LwFlXVHyhAcWyKaw==";
UserData.PasswordFormat = "Hashed";
UserData.HashAlgorithm = "PBKDF2";
UserData.PasswordSalt = "FaED9QsIV9HD95m8FO5OSA==";
UserData.RegistrationStatus = "Approved";
UserData.EmailStatus = "Approved";
UserData.CreatedUtc = DateTime.Today;
Context.Home_Orchard_Users_UserPartRecord.Add(UserData);
//Context.SaveChanges();
i = i + 1;
progress = ((float)i / nCount) * 100;
Console.Write("\r{0}%", progress);
Thread.Sleep(50);
}
Why I can't insert the second time? The Id is the primary key and it's not autogenerated so it has to be input manually.

EF update is inserting and into a different table

I have an MVC 5 website using EF6 code first.
The website will track golf results at events.
Here are my pocos:
public class Event
{
public int EventId { get; set; }
public string VenueName { get; set; }
public string CourseName { get; set; }
public String FirstTeeOff { get; set; }
public DateTime EventDate { get; set; }
public decimal Fee { get; set; }
public virtual ICollection<Result> Results { get; set; }
}
public class Golfer
{
public int GolferId { get; set; }
public string FirstName { get; set; }
public string Surname { get; set; }
public int CurrentHandicap { get; set; }
public string Email { get; set; }
public string Telephone { get; set; }
public virtual ICollection<Result> Results { get; set; }
}
public class Result
{
public int ResultId { get; set; }
public Golfer Golfer { get; set; }
public Event Event { get; set; }
public bool Attendance { get; set; }
public int HandicapPlayed { get; set; }
public int ScoreCarded { get; set; }
public int LongestDriveWins { get; set; }
public int NearestPinWins { get; set; }
public Result()
{
Event = new Event();
Golfer = new Golfer();
}
}
The POST edit action for my Result is as follows:
[HttpPost]
[Authorize]
public ActionResult Edit(ResultViewModel resultVM)
{
try
{
DomainClasses.Result resultDomain = _context.Results.Find(resultVM.GolferResults[0].ResultId);
resultDomain.Attendance = resultVM.GolferResults[0].Attendance;
resultDomain.HandicapPlayed = resultVM.GolferResults[0].HandicapPlayed;
resultDomain.ScoreCarded = resultVM.GolferResults[0].ScoreCarded;
resultDomain.LongestDriveWins = resultVM.GolferResults[0].LongestDriveWins;
resultDomain.NearestPinWins = resultVM.GolferResults[0].NearestPinWins;
_context.Results.Attach(resultDomain);
_context.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
I'm getting an error on the SaveChanges. I've used EF Profiler and it showed that it was trying to insert into the Event table:
INSERT [dbo].[Events]
([VenueName],
[CourseName],
[FirstTeeOff],
[EventDate],
[Fee])
VALUES (NULL,
NULL,
NULL,
'0001-01-01T00:00:00' /* #0 */,
0 /* #1 */)
SELECT [EventId]
FROM [dbo].[Events]
WHERE ##ROWCOUNT > 0
AND [EventId] = scope_identity()
Any idead why?
It's most likely because you create instances of the related entities in the Result constructor:
Event = new Event();
Golfer = new Golfer();
Remove those lines from the constructor.

Get next pPrimary key id with lambda expression

I'm using Entity Framework 5 and I need to get next id in table like
1
2
3
4
I want to get next id, when my id is 1 want to get next id 2
public class Level
{
[Key]
public int LevelID { get; set; }
public string Name { get; set; }
public double Cost { get; set; }
public int Statue { get; set; }
public int CourseID { get; set; }
public int? SessionCount { get; set; }
public int? SessionAttend { get; set; }
public DateTime? DateAdded { get; set; }
public Guid UserAddID { get; set; }
public Guid userEditID { get; set; }
public DateTime DateUpdated { get; set; }
public bool DelFlag { get; set; }
public DateTime? DelDate { get; set; }
public Guid? UserDelID { get; set; }
}
Thanks for your help.
public int getNextId(int id)
{
var nextEntities = repository.Query<Levels>().OrderBy(d=>d.LevelId)
.Where(l=>l.LevelId>id)
.Take(1).SingleOrDefault();
return nextEntities != null ? nextEntities.LevelId : ++id; //or return 0 on your choice
}
To get the next LevelId that would be assigned for a new row you could probably use this:
var nextId = db.Levels.OrderBy(x => x.LevelId).Last().LevelId + 1;
I probably wouldn't recommend this though. The whole idea wreaks of bad code smell to me.