I am currently stuck on adding a new child entity to my database using lamda queries. The structure of my database is that Area
has a one to many relationship with Shifts
In my seeding database I populate the Shifts while creating the Areas:
new Area()
{
AreaDesc = "Area 1",
AreaActive = true,
AreaCreatedDate = DateTime.Now,
SHFID = new Shift()
{
StartTime = new TimeSpan (5,30,00),
EndTime = new TimeSpan (11, 00, 00),
RequiredResources = 2,
ShiftDesc = "AM Shift",
ShiftDayID = 1
}
}
That works fine, where I am struggling and probably due to a simple lack of understanding on entity frameworks abilities is adding a new Shift to an existing Area .
So far I have the following
var AreaVal = _context.Areas.Where(a => a.AreaID == AreaID).ToList();
var Shift = new Shift
{
Area = AreaVal,
StartTime = StartTime,
EndTime = EndTime,
ShiftDayID = model.ShiftDayID,
ShiftDesc = model.ShiftDesc
};
Thinking that once I had the correct Area (I have the ID coming from the model) I could load the Area and pass it as the Area parameter in the Shift and entity framework would know what to do.
The Error I get in the parser is:
Cannot implicitly convert type (Generic.List to Models.Area.
I have also considered going from the other direction using _context.Areas.Update()
but have been unable to work that one out very well.
Shift.cs
public class Shift
{
[Key]
public int SHFID { get; set; }
public TimeSpan StartTime { get; set; }
public TimeSpan EndTime { get; set; }
public int RequiredResources { get; set; }
public string ShiftDesc { get; set; }
public int ShiftDayID { get; set; }
public DateTime ShiftExDateStart { get; set; }
public DateTime ShiftExDateEnd { get; set; }
public int ShiftExLevel { get; set; }
public TimeSpan ShiftExStartTime { get; set; }
public TimeSpan ShiftExEndTime { get; set; }
public Area Area { get; set; }
}
Area.cs
public class Area
{
[Key]
public int AreaID { get; set; }
public string AreaDesc { get; set; }
public Boolean AreaActive { get; set; }
public DateTime AreaCreatedDate { get; set; }
public List<Shift> SHFID { get; set; }
public Company Company { get; set;}
}
You are on the right track.
AreaVal
needs to be a single entity ( Area
), not a list of entities ( List<Area>
). Then it should work as expected.
Change the line:
var AreaVal = _context.Areas.Where(a => a.AreaID == AreaID).ToList();
to
var AreaVal = _context.Areas.Where(a => a.AreaID == AreaID).Single();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.