Loop Adding Records Throws Exception - asp.net-mvc

Does anyone know what the proper way of adding records using loops?
I have a system that handles Inventory, Currently I need to be able to Mass Create inventory as creating 50-100 identical items with different ID's would be tedious, What I did was create a MassCreate viewmodel that would essentially take a StartID and an EndID and a base Inventory Class and in the controller loop through the difference between those two ID's and create a record
The ViewModel isn't an issue and passes the data just fine:
public class MassCreateInventoryViewModel
{
public Inventory InventoryBase { get; set; }
public int StartID { get; set; }
public int EndID { get; set; }
public IEnumerable<SelectListItem> Products { get; set; }
}
I read somewhere that the db.SaveChanges() should be outside of the loop as it should only be called once:
for (int inventoryID = viewModel.StartID; inventoryID <= viewModel.EndID; inventoryID++)
{
Inventory newInventory = new Inventory
{
InventoryID = inventoryID,
ProductID = viewModel.InventoryBase.ProductID,
DateEdited = DateTime.Now,
EditedByUserID = WebSecurity.CurrentUserId,
CustomProperties = viewModel.InventoryBase.CustomProperties
};
Database.Inventories.Add(newInventory);
if (newInventory.CustomProperties != null && newInventory.CustomProperties.Any())
{
foreach (CustomDataType dt in newInventory.CustomProperties.Select(x => x.DataType).ToList())
{
Database.Entry(dt).State = EntityState.Unchanged;
}
}
}
Database.SaveChanges();
}
But when I try looping, it stores the first record just fine then throws a Collection was modified; enumeration operation may not execute. Exception. When I include the Database.SaveChanges() after the Add method, it throws A The property 'InventoryID' is part of the object's key information and cannot be modified. error.
The InventoryID is the Key in this table but has been set so that I can input my own ID.
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
[Display(Name = "Inventory ID")]
public new int InventoryID { get; set; }
The Custom Property is split into two models, the first being the base class.
public class CustomProperty
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int CustomPropertyID { get; set; }
public int CustomDataTypeID { get; set; }
[ForeignKey("CustomDataTypeID")]
public CustomDataType DataType { get; set; }
public string PropertyValue { get; set; }
}
and the second being the model thats mapped to the database:
[Table("CustomInventoryProperty")]
public class CustomInventoryProperty : CustomProperty
{
public int InventoryID { get; set; }
[ForeignKey("InventoryID")]
public virtual Inventory Inventory { get; set; }
}

Replace your for loop with this:
var dateEdited = DateTime.Now;
for (int inventoryID = viewModel.StartID; inventoryID <= viewModel.EndID; inventoryID++)
{
Inventory newInventory = new Inventory
{
InventoryID = inventoryID,
ProductID = viewModel.InventoryBase.ProductID,
DateEdited = dateEdited,
EditedByUserID = WebSecurity.CurrentUserId
};
if(viewModel.InventoryBase.CustomProperties != null)
{
newInventory.CustomProperties = new List<CustomProperties>();
foreach(var customProperty in viewModel.InventoryBase.CustomProperties)
{
newInventory.CustomProperties.Add(customProperty);
}
}
Database.Inventories.Add(newInventory);
Database.SaveChanges();
}

Related

How to display the details of a row from multiple tables using LINQ?

I'm stuck here on a situation wherein I should display the details of a person together with the list of his/her allocations. I've done creating a view model to pass the data to a view but the result is:
The model item passed into the dictionary is of type 'System.Data.Entity.Infrastructure.DbQuery`1[EKCMIDTA.ViewModels.EmployeeDetailsVM]', but this dictionary requires a model item of type 'EKCMIDTA.ViewModels.EmployeeDetailsVM'.
For the TicketScannings table, I just wanted to know whether the person has used some of the allocations, and to count how many were used, regardless it it's null.
I hope someone can help me with this.
Thanks!
Controller:
public ActionResult GetDetails(int empId)
{
var employeeInformation = identityContext.AspNetUsers.Find(empId);
var employeeDetails = dbContext.TicketAllocations.Include(a => a.AllocationCategory).Where(t => t.CMId == empId).ToList();
var query = (from alloc in dbContext.TicketAllocations
join scan in dbContext.TicketScannings
on alloc.Id equals scan.TicketAllocationId
join card in dbContext.CardNumberAssignments
on alloc.CMId equals card.CMId into a
from card in a.DefaultIfEmpty()
join reserve in dbContext.ReservedCardNumbers
on card.CardNumberId equals reserve.Id into b
from reserve in b.DefaultIfEmpty()
where (alloc.CMId == empId)
select new EmployeeDetailsVM()
{
Employee = new Employee()
{
FirstName = employeeInformation.FirstName,
LastName = employeeInformation.LastName,
CMId = employeeInformation.Id,
CardNumber = reserve == null ? "No Card Number yet" : reserve.CardNumber,
QRCode = card == null ? "No QR Code yet" : card.QRCode
},
GetTicketAllocations = employeeDetails
});
return View(query);
View Model:
public class EmployeeDetailsVM
{
public Employee Employee { get; set; }
public IEnumerable<Allocation> GetTicketAllocations { get; set; }
}
public class Employee
{
public string CMId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string CardNumber { get; set; }
public string QRCode { get; set; }
}
public class Allocation
{
public int AllocationId { get; set; }
public string AllocationName { get; set; }
public int Quantity { get; set; }
public bool IsActive { get; set; }
public string CreatedBy { get; set; }
public DateTime CreatedDate { get; set; }
public string ModifiedBy { get; set; }
public DateTime ModifiedDate { get; set; }
}
View:
#model EKCMIDTA.ViewModels.EmployeeDetailsVM
Looks like your view is only accepting a model of a single EmployeeDetailsVM, but you're passing in a query which would could return multiple.
so you can change #model EKCMIDTA.ViewModels.EmployeeDetailsVM to #model IEnumerable<EKCMIDTA.ViewModels.EmployeeDetailsVM>
or change your GetDetails action to return View(query.FirstOrDefault());
Edit based on comment
public ActionResult GetDetails(int empId)
{
var employeeInformation = identityContext.AspNetUsers.Find(empId);
var employeeTickets = dbContext.TicketAllocations.Include(a => a.AllocationCategory).Where(t => t.CMId == empId).ToList();
var employeeDetails = (from alloc in dbContext.TicketAllocations
join scan in dbContext.TicketScannings
on alloc.Id equals scan.TicketAllocationId
join card in dbContext.CardNumberAssignments
on alloc.CMId equals card.CMId into a
from card in a.DefaultIfEmpty()
join reserve in dbContext.ReservedCardNumbers
on card.CardNumberId equals reserve.Id into b
from reserve in b.DefaultIfEmpty()
where (alloc.CMId == empId)
select new EmployeeDetailsVM()
{
Employee = new Employee()
{
FirstName = employeeInformation.FirstName,
LastName = employeeInformation.LastName,
CMId = employeeInformation.Id,
CardNumber = reserve == null ? "No Card Number yet" : reserve.CardNumber,
QRCode = card == null ? "No QR Code yet" : card.QRCode
}
}).FirstOrDefault();
if (employeeDetails != null)
employeeDetails.GetTicketAllocations = employeeTickets;
return View(employeeDetails);
}

The entity type <type> is not part of the model from the current context

I get this error (An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code
The entity type tblMessage is not part of the model for the current context.) and have tried fixes I found online but they didnt seem to help. I also did somethin similar for another database tabel earlier in the code.
Im trying to retrieve messages form my database table called tblMessages.
Constructor:
public JsonResult ConversationWithContact(int contact)
{
if (Session["UserID"] == null)
{
return Json(new {status = "error", message = "User is not logged in"});
}
//var currentUser = (Models.tblUser)Session["UserID"];
var conversations = new List<Models.tblMessage>();
using (var db = new Models.ChatContext())
{
int currentUserId = (int)Session["UserID"];
var currentUser = db.Users.FirstOrDefault(x => x.Id == currentUserId);
conversations = db.Conversations.Where(c => (c.receiverId == currentUser.Id
&& c.senderId == contact) ||
(c.receiverId == contact
&& c.senderId == currentUser.Id))
.OrderBy(c => c.created_at)
.ToList();
}
return Json(
new {status = "success", data = conversations},
JsonRequestBehavior.AllowGet
);
}
Context:
public ChatContext() : base("TrinityEntities")
{
}
public static ChatContext Create()
{
return new ChatContext();
}
public DbSet<tblUser> Users { get; set; }
public DbSet<tblMessage> Conversations { get; set; }
Database model class:
public class tblMessage
{
public tblMessage()
{
status = messageStatus.Sent;
}
public enum messageStatus
{
Sent,
Delivered
}
public int Id { get; set; }
public int senderId { get; set; }
public int receiverId { get; set; }
public string message { get; set; }
public messageStatus status { get; set; }
public System.DateTime created_at { get; set; }
}
Here is issue with Table Mapping to database. each entity will be set up to map to a table with the same name as the DbSet<TEntity> property that exposes to the derived context. If no DbSet<TEntity> is included for the given entity, the class name is used.
as you set in your code Users and Conversations is not table name. for that you can customize also refere https://learn.microsoft.com/en-us/ef/core/modeling/relational/tables
and use Data Annotations for specify table name.
public messageStatus status { get; set; }
i think this property is not not part of your table column so you have to specify [NotMapped] Data Annotations.
after changes and adding Data Annotations to table context and table look likes.
public class ChatContext : DbContext
{
public ChatContext()
{
}
public virtual DbSet<tblUser> Users { get; set; }
public virtual DbSet<tblMessage> Conversations { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=test;Trusted_Connection=True;MultipleActiveResultSets=true");
}
}
}
and your models(tables) entities look like.
[Table("tblMessage")]
public class tblMessage
{
public tblMessage()
{
status = messageStatus.Sent;
}
public enum messageStatus
{
Sent,
Delivered
}
public int Id { get; set; }
public int senderId { get; set; }
public int receiverId { get; set; }
public string message { get; set; }
[NotMapped]
public messageStatus status { get; set; }
public System.DateTime created_at { get; set; }
}
[Table("tblUser")]
public class tblUser
{
public int id { get; set; }
public string name { get; set; }
}
now you can access your Conversations and Users after adding [Table("<table-name>")] Data-Annotations.
also you can use Fluent API for table mapping.
after using table mapping table after debug code image like.
i hope it helps you and let me know if require any more information. :)

What is the right syntax for this joined EF Linq query

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()
};

Get data from two tables (view and list) with LinQ and return into one view (code MVC-C#)

I have two tables: tour and hotel I want to execute query with join and get the result in the View.
How to view data from two tables as figure below?
enter link description here
in the Controller I have this code :
public ActionResult DetailView(string strID)
{
var id_tour = (from data1 in _db.Tours
join dataview2 in _db.TypeOfCosts on data1.ID_TourCost equals dataview2.ID_TourCost
where (data1.ID_Tour == strID) && (data1.ID_TourCost == dataview2.ID_TourCost)
select new
{
data1.TourName,
data1.ID_Tour,
data1.DepartureDay,
data1.DeparturePosition,
data1.AvailableRoom,
dataview2.AdultCost,
dataview2.ChildrenCost,
dataview2.BabyCost,
}).FirstOrDefault();
var view_tour = new DetailModels(id_tour.TourName, id_tour.ID_Tour, Convert.ToDateTime(id_tour.DepartureDay), id_tour.DeparturePosition,
Convert.ToInt32(id_tour.AvailableRoom),
Convert.ToInt32(id_tour.AdultCost), Convert.ToInt32(id_tour.ChildrenCost), Convert.ToInt32(id_tour.BabyCost));
return View(view_tour);
}
[HttpPost]
public ActionResult DetailView(DetailModels model)
{
var id_hotel = from data2 in _db.Tours
join dataview3 in _db.TourPrograms on data2.ID_Tour equals dataview3.ID_Tour
join dataview4 in _db.Programs on dataview3.ID_TourProgram equals dataview4.ID_TourProgram
join dataview5 in _db.Hotels on dataview4.ID_Hotel equals dataview5.ID_Hotel
where (data2.ID_Tour == dataview3.ID_Tour) &&
(dataview3.ID_TourProgram == dataview4.ID_TourProgram) && (dataview4.ID_Hotel == dataview5.ID_Hotel)
select new
{
dataview5.HotelName,
dataview5.HotelAddress,
dataview5.HotelPhoneNumber,
};
// chuyền dữ liệu vào như thế nào
return RedirectToAction("DetailView", "Tourpackage");
}
in the Model I have this code:
enter code here public class DetailModels
{
public string TourName { get; set; }
public string ID_Tour { get; set; }
public DateTime DepartureDay { get; set; }
public string DeparturePosition { get; set; }
public int AvailableRoom { get; set; }
public string HotelName { get; set; }
public string HotelAddress { get; set; }
public int HotelPhoneNumber { get; set; }
public int AdultCost { get; set; }
public int ChildrenCost { get; set; }
public int BabyCost { get; set; }
public DetailModels(string tourname, string idtour, DateTime dapartureday, string departureposition, int availableroom,
int adultcost, int childrencost, int babycost)
{
this.TourName = tourname; this.ID_Tour = idtour; this.DepartureDay = dapartureday; this.DeparturePosition = departureposition;
this.AvailableRoom = availableroom;
this.AdultCost = adultcost; this.ChildrenCost = childrencost; this.BabyCost = babycost;
}
hope to the help of everyone............thanks
When You are using MVC i strongly recommend You to use Entity Framework. If You never use it check this out: http://www.pluralsight-training.net/microsoft/Courses/TableOfContents?courseName=aspdotnet-mvc3-intro - very good video-tutorial.
I assume that Tour-Hotel relation is typical many-to-many. Mapped by EF class Tour will have property Hotels and vice versa. If You pass for example Tour to view #Model.Hotels give You collection of related hotels. And BTW do some refactoring code,please:)

Populating a linking table in a many-to-many relationship

I am trying to get to grips with EF4 CTP5. I have two classes that have a many-to-many relationship: Member and MemberGroup. CTP5 Code First generated two tables (Members and MemberGroups) and also a third named MemberGroupMembers that has two columns (MemberGroupId and MemberId) So far everything is as I was expecting it to be. I have seeded the database with some Members and MemberGroups. The problem is that I cannot find how to assign one or more MemberGroups to a Member, which would result in inserting a row into the MemberGroupMembers table for each MemberGroup that the Member is assigned to.
public class Member
{
public int Id { get; set; }
public Guid SecureId { get; set; }
public DateTime JoinedOn { get; set; }
public virtual ICollection<MemberGroup> MemberGroups { get; set; }
}
public class MemberGroup
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime CreatedOn { get; set; }
public virtual ICollection<Member> Members { get; set; }
}
public class CTP5testContext : DbContext
{
public CTP5testContext() : base("CTP5test") { }
public DbSet<Member> Members { get; set; }
public DbSet<MemberGroup> MemberGroups { get; set; }
}
public class CTP5testContextInitializer : DropCreateDatabaseIfModelChanges<CTP5testContext>
{
protected override void Seed(CTP5testContext context)
{
new List<Member>
{
new Member
{
Id = 1,
SecureId = Guid.NewGuid(),
JoinedOn = DateTime.Now
}
,
new Member
{
Id = 2,
SecureId = Guid.NewGuid(),
JoinedOn = DateTime.Now
}
}.ForEach(m => context.Members.Add(m));
var memberGroup = new MemberGroup()
{
Id = 1,
Name = "MemberGroup 1",
CreatedOn = DateTime.Now
};
context.MemberGroups.Add(memberGroup);
// How can I assign Member 1 to MemberGroup 1 ?????
context.SaveChanges();
}
}
I hope that it is clear what I am trying to do here and that someone can give me an example of how to achieve this.
Regards,
Erwin
You must use collections defined in your POCO classes. So if you want to assign member1 to memberGroup you will simply call:
memberGroup.Members.Add(member1);

Resources