I'm trying to insert records in my Concursos table by this entity
public class Concurso
{
public int Id { get; set; }
.....
public DateTime FechaArchivo { get; set; }
public DateTime FechaConsulta { get; set; }
public DateTime FechaOrientativa { get; set; }
public DateTime FechaInsercion { get; set; }
....
}
public int AddConcursos()
{
_context.Concursos.AddRange(
new Concurso { Id = 2077196, ...., FechaArchivo = new DateTime(2020,7,7), FechaOrientativa
= new DateTime(2021,7,7), FechaInsercion = new DateTime(2020,7,7),...
);
var dbResult = _context.SaveChanges();
return dbResult;
}
But when I execute the method I get this error
any idea, please?
Thanks
Related
I'm implementing an ASP.NET Core 3.1 app. I have implemented following code to insert record in SQL Server database via EF Core but each time I save data, it inserts two records in PersonRequester and Requester table. I appreciate if anyone suggests me how I can prevent reinserting records.
Requester ap = new Requester();
ap.Address = RequesterViewModel.Requestervm.Address;
ap.RequesterType = RequesterViewModel.Requestervm.RequesterType;
ap.Description = RequesterViewModel.Requestervm.Description;
ap.Name = RequesterViewModel.Requestervm.Name;
var pa = new PersonRequester()
{
BirthCertificateNo = RequesterViewModel.personRequestervm.BirthCertificateNo,
IssuePlace = RequesterViewModel.personRequestervm.IssuePlace,
NationalCode = RequesterViewModel.personRequestervm.NationalCode,
Requester = ap
};
using (var context = new DBContext())
{
context.PersonRequester.Attach(pa);
try
{
context.SaveChanges();
}
catch (Exception e)
{
throw e;
}
}
public partial class Requester
{
public Requester()
{
PersonRequester = new HashSet<PersonRequester>();
}
public int RequesterId { get; set; }
public int RequesterType { get; set; }
public string Address { get; set; }
public string Description { get; set; }
public string Name { get; set; }
public virtual EntityType RequesterTypeNavigation { get; set; }
public virtual ICollection<PersonRequester> PersonRequester { get; set; }
}
public partial class PersonRequester
{
public int RequesterId { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public int RequesterType { get; set; }
public string NationalCode { get; set; }
public string BirthCertificateNo { get; set; }
public string IssuePlace { get; set; }
public virtual Requester Requester { get; set; }
public virtual EntityType RequesterTypeNavigation { get; set; }
}
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();
}
I get an error when I try to insert a value in my Table.
_dltype is an object of type BRIDownloadType.
using (var db = new BRIDatabase())
{
foreach (var client in db.BRIClients)
{
var todo = new BRIToDo
{
BRIClient = client,
BRIDownloadType = _dltype,
};
db.BRIToDos.Add(todo);
}
db.SaveChanges();
}
Now I get the error:
An Explict Value can't be inserted in the Idendity Column in the BRIDownloadTypes-Table when IDENTITY_INSERT is OFF.
My 2 Tables are
BRIDownloadType
public class BRIDownloadType
{
[Key]
public int DlTypeId { get; set; }
[Required]
[StringLength(15)]
public string DlType { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public virtual ICollection<BRIToDo> BRIToDo { get; set; }
}
BRITodo
public class BRIToDo
{
[Key]
public int ToDoId { get; set; }
[ForeignKey("BRIClient")]
public int ClientId { get; set; }
[ForeignKey("BRITask")]
public int TaskId { get; set; }
public virtual BRIClient BRIClient { get; set; }
public virtual BRITask BRITask { get; set; }
[ForeignKey("BRIDownloadType")]
public int DlTypeId { get; set; }
public virtual BRIDownloadType BRIDownloadType { get; set; }**
}
The interesting thing is, if I do something with my _dltype object, I can use it.
The following code is working and I don't understand why, I'm inserting the exact same object.
using (var db = new BRIDatabase())
{
var dl = db.BRIDownloadTypes.FirstOrDefault(c => c.DlTypeId == _dltype.DlTypeId);
foreach (var client in db.BRIClients)
{
var todo = new BRIToDo
{
BRIClient = client,
BRIDownloadType = _dltype,
};
db.BRIToDos.Add(todo);
}
db.SaveChanges();
}
Can anybody explain to me, why the last approach is working and the first is throwing that error? I just added the line
var dl = db.BRIDownloadTypes.FirstOrDefault(c => c.DlTypeId == _dltype.DlTypeId)
But I'm still inserting the same object. If I insert the Id of the object instead of the object it is also working fine. I have no idea whats going on there.
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.
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.