I am trying to get the last value of a record from the database. I am using entity framework. I am trying to get the last value of the balance and deduct the amount user enters to get the new balance. I am new to this and trying to create a simple expense management system.
My controller
public ActionResult Create([Bind(Include = "ExpenseId,ExpenseFor,DateTime,Amount,Balance,RowVersion")] Expense expense)
{
if (ModelState.IsValid)
{
var a = db.Expenses.Select(b => b.Balance);
var c = a.Last();
expense.Balance = c - expense.Amount;
db.Expenses.Add(expense);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(expense);
}
return View(expense);
}
My model looks like this
public class Expense
{
public int ExpenseId { get; set; }
public string ExpenseFor { get; set; }
public DateTime DateTime { get; set; }
public Decimal? Amount { get; set; }
public Decimal? Balance { get; set; }
[Timestamp]
public byte[] RowVersion { get; set; }
}
When I try to create new records, it says that the Method cannot be translated into a store expression. I would really appreciate any help with this.
If you use SQL server, it's no wonder .Last()function is not going to work.
There is no such things as (select last) in SQL server, so Entity basicaly fails to translate it to a database SQL server language. This is what you have to do :
var v = db.Expenses.OrderByDescending(t => t.ColumnName).First();
Or something similar, depending on what you want.
Try to think of a way to turn the query around and use First() ... or FirstOrDefault() if your are afraid of potential null values.
Your own solution :
var v = db.Expenses.OrderByDescending(t => t.ExpenseId).First();
Related
I'm going for the edit data by ProuctId.i have 2 table like Product and productitems.so i m click on edit go for the id by getting data but that time i m fetch data by id in the product table is getting propare but after going for the list productitems data getting like this error.
this is my class ProductItmes:
[Table("ProductItems ")]
public class ProductItems
{
[Key]
public int id { get; set; }
[ForeignKey("Products")]
public int pid {get; set;}
public int Qty { get; set; }
public Decimal Rate { get; set; }
public virtual Products Products { get; set; }
}
this is my api method:
public ActionResult GetProductByid(int id)
{
var Pro = db.Product.Find(id);
var ProItemList = db.Promotion_ctc.Where(x => x.pid == Pro.id).ToList();//here i am getting list of items by productid
var Details = new
{
Pro.id,
Pro.name,
Pro.image_url,
ProItemList
};
return Json(new { data = Details });
}
idk where is my problem any one know please let me know.
When working with MVC and Entity Framework, there are cases where we make our child entities reference the parent, like you did, by declaring this property here:
public virtual Products Products { get; set; }
it's ok for entity framework, but it's not when you try to serialize this.
What's going on:
The serializer will try to serialize the parent, which has a collection of ProductItem.
The serializer tries to serialize each child.
The child has a reference to parent, so the serializer tries to serialize the parent again.
Infinite loop.
That's why people use ViewModels. Instead of just returning your entities from your action, project them into a view model, and return it. Actually, you're returning an anonymous object containing a ProItemList, which I'd guess it's a List of ProductItems. Just create a view model for it:
public class ProductItemViewModel
{
public int ItemId { get; set; }
public int ProductId {get; set;}
public int Qty { get; set; }
public Decimal Rate { get; set; }
// public virtual Products Products { get; set; } NO PRODUCT HERE
}
...then fix your action to return a List of ProductItemViewModel, instead of returning directly ProductItems, like this:
var ProItemList = db.Promotion_ctc.Where(x => x.pid == Pro.id)
.Select(i => new ProductItemViewModel
{
ItemId = i.ItemId,
ProductId = i.ProductId,
Qty = i.Qty,
Rate = i.Rate
})
.ToList();
var Details = new
{
Pro.id,
Pro.name,
Pro.image_url,
ProItemList
};
return Json(new { data = Details });
}
send only required columns to ui
like this
var passToUi = from s in listResult
select new { s.Id, s.Name };
return Json(passToUi, JsonRequestBehavior.AllowGet);
Well im doing a application where i have a model like this
public class Saldo
{
public Saldo()
{
Expenses = new List<Expese>();
Incomes = new List<Income>();
}
public int SaldoId { get; set; }
public List<Expense> Despesas { get; set; }
public List<Income> Rendimentos { get; set; }
public string ApplicationUserId { get; set; }
}
what i want to do is add a single expense to the list but it is not working, when i output on the console the count it is always null
in the controller im doing this:
public ActionResult Create([Bind(Include = "ExpenseId,TipoDespesaId,DespesaDescricao,DespesaValor,TipoPagamentoId,Data,Comentario")] Expense expense)
{
var userId = User.Identity.GetUserId();
if (ModelState.IsValid)
{
var balance = db.Balance.Where(d => d.ApplicationUserId == userId).FirstOrDefault();
expense.ApplicationUserId = userId;
if (balance == null)
{
Balance s = new Balance();
s.Expense.Add(expense);
s.ApplicationUserId = userId;
db.Balance.Add(s);
}
else
{
Balance.Expense.Add(expense);
}
db.Expense.Add(expense);
db.SaveChanges();
return RedirectToAction("Index");
}
The expense comes from the form and is passed to the Action
I created a new instance of Balance it worked adding the ApplicationUserId but the expense on the list didnt work, can someone explain me why it happen?
Ps: Sorry for my bad english
Perhaps it's just lost in the translation, but your model doesn't make sense. You have a list of Expense called "Despesas" but in the constructor you call it "Expenses" Whatever that list is called is what you need to add your expense object to. Instead of
s.Expense.Add(expense);
it would be
s.Despesas.Add(expense);
I have this maintenance scheduling system, and in im using MVC C# Entity Framework,
I have this table
Truck Table that has - truck id, registration no., kilometer run reading, and i have an JobOrder Table, i want to get the truck id in the truck table so that i can add a JobOrder on a specific Truck i have this JobOrder Controller
public ActionResult AddJobOrder(JobOrderModel jo, int id)
{
var AddJobOrder = db.trucks.FirstOrDefault(s => s.id == id);
var addjo = new joborder()
{
truck_no = AddJobOrder,
description = jo.Description,
worked_performed = jo.worked_performed,
quantity = jo.Quantity,
spare_parts = jo.SpareParts,
run = jo.kilometer_run,
date_finished = jo.DateFinished,
date_started = jo.DateFinished,
};
if (!ModelState.IsValid)
{
db.joborders.Add(addjo);
db.SaveChanges();
return View(jo);
}
return View(jo);
}
I receive the following error:
Error 4 Cannot implicitly convert type 'Pms_system.truck' to 'int'
This is my model
public class JobOrderModel
{
public int truck_no { get; set; }
public DateTime DateStarted { get; set; }
public DateTime DateFinished { get; set; }
public string SpareParts { get; set; }
public int Quantity { get; set; }
public string Description { get; set; }
public int kilometer_run { get; set; }
public string worked_performed { get; set; }
}
Please help me to get the truck id.
It looks like this is just a matter of getting the ID out of the truck - after all, your oddly-named AddJobOrder variable is presumably of type Truck or something similar. I suspect you just need something like:
truck_no = AddJobOrder.id,
After all, that's how you're getting at the truck ID in the query just beforehand. It's not entirely clear why you need the query at all if you only need the truck ID, which has been provided to the method anyway - all you're doing at the moment is allowing you to check whether or not there is such a record, although you should then actually do the check by seeing whether FirstOrDefault returned null.
I would also strongly advise you to take a good look at the names you're using, both in terms of capitalization and semantic names too. (Your AddJobOrder variable should be called truck or something similar by the sounds of it. The fact that it's the same name as the method is doubly confusing!)
This question is part B of my other question here:
Inefficient MVC ViewModel Making Multiple Calls to the Database?
I knew multiple calls to the db was a bad idea. But, I guess my real question is if I use my last chunk of code or speti43's example let's say like this in my model constructor to eliminate multiple db calls:
Public Class OrdersSummary{
...
Public ???? GetOrders(){
var ordersInMemory = orders.ToList();
decimal? GrossProfitTotal = ordersInMemory.Sum(s => s.Profit);
decimal? CommissionTotal = ordersInMemory.Sum(s => s.Commission);
decimal? NetProfitTotal = GrossProfitTotal + CommissionTotal;
return ?????
}
}
How do I pass those seperate but similar pieces of data to the controller? I was trying to use a tuple like this based on some other SO article recommendation here:
How to return multiple values from a function in C# (ASP.NET)?
public Tuple<IEnumerable<dynamic>, decimal?, decimal?, decimal?> GetOrders(string sortOrder, string searchString)
{
...
return new Tuple<IEnumerable<dynamic>,decimal?,decimal?,decimal?> (ordersInMemory, GrossProfitTotal, CommissionTotal, NetProfitTotal);
}
Does this sound reasonable? Then I have no idea how to reference the tuple in my controller:
var ordersummary = new OrdersSummary();
var viewModel = new OrderSummary
{
???? cause I have no idea how to reference the tuple
};
return View(viewModel);
The other issue is I'm not entirely sure I'm building the properties correct in my view model. Currently I have it like this for the four pieces of data and then individual properties of the Orders list:
public class OrderSummary
{
public IEnumerable<dynamic> Orders { get; set; }
public decimal GrossProfitTotal { get; set; }
public decimal CommissionTotal { get; set; }
public decimal NetProfitTotal { get; set; }
//Orders Table Properties
public int OrderNumber { get; set; }
public DateTime OpenTime { get; set; }
//more properties here that correspond to the Orders table.
}
It seems like I might need to structure the tuple properties different in the view model? If so, what syntax?
I think I might know what goes in the View if I knew what goes in the controller. Is this even the correct way to go about it? I got this whole view model structure idea from step 8 on the MVCMUsicStore tutorial:
http://www.asp.net/mvc/tutorials/mvc-music-store/mvc-music-store-part-8
After much cursing and even more red squiggly lines, I figured out a couple ways to do this and neither involves a tuple:
First Method:
ViewModel:
public IEnumerable<OrderSummary> Orders { get; set; }
public decimal? GrossProfitTotal { get { return Orders.Sum(s => (decimal)s.Profit); } }
public decimal? CommissionTotal { get { return Orders.Sum(s => (decimal)s.Commission); } }
public decimal? NetProfitTotal { get { return GrossProfitTotal + CommissionTotal; } }
Controller:
var orderssummary = new OrdersSummary();
var viewModel = new OrderSummary
{
Orders = orderssummary.GetOrders(sortOrder, searchString),
}
return View(viewModel);
Second Method:
ViewModel:
public IEnumerable<OrderSummary> Orders { get; set; }
public decimal? GrossProfitTotal { get; set; }
public decimal? CommissionTotal { get; set; }
public decimal? NetProfitTotal { get; set; }
Controller:
var orderssummary = new OrdersSummary();
var orderslist = orderssummary.GetOrders(sortOrder, searchString);
decimal? grossprofittotal = orderslist.Sum(s => (decimal)s.Profit);
decimal? commissiontotal = orderslist.Sum(s => (decimal)s.Commission);
decimal? netprofittotal = orderslist.Sum(s => (decimal)s.Profit + s.Commission);
var viewModel = new OrderSummary
{
Orders = orderslist,
GrossProfitTotal = grossprofittotal,
CommissionTotal = commissiontotal,
NetProfitTotal = netprofittotal,
};
return View(viewModel);
View (for first and second methods):
#foreach (var item in Model.Orders){
#item.OrderNumber
#item.OpenTime
etc.
}
#Model.CommissionTotal
#Model.GrossProfitTotal
#Model.NetProfitTotal
I am currently using number 1 as it appears a little cleaner. I believe it is now looping through my Ienumerable for the other values instead of hitting the db for each one? I would love to figure out how to calculate all values on a single loop.
It also appears I don't even really need a viewmodel for number 1, but I'll be adding other pieces of info to the view like chart data, so I will leave my options open.
I'm always interested to know people's thoughts and if they have a preference for either or a whole better way.
I have read a few articles about .Net Entity Framework that really didn't make me want to try it out. But now I have started a small test.
I set up a MVC 3 site that will handle economy transactions for my family, just for fun. So I setup Membership provider and get the login functions working. Usually I use the Membership Guid in a column to identify each row to a specific user.
I setup this class in my project:
namespace mEconomy.Models
{
public class Transaction
{
public Guid UserID { get; set; }
public int TransactionID { get; set; }
public DateTime Date { get; set; }
public string Text { get; set; }
public string Category { get; set; }
public decimal Amount { get; set; }
}
public class TransactionDBContext : DbContext
{
public DbSet<Transaction> Transactions { get; set; }
}
}
Works fine but I get the information on all users. If user A logs on and creates a few transaction then user B can create an account and see them. What is best practice here? How do I keep the user data separated?
I even tried setting the UserID as a private like this:
private Guid UserID = (Guid)Membership.GetUser().ProviderUserKey;
But that didn't work at all.
In your controller, use a linq query or the fluent api to retrieve only the desired entries:
TransactionDBContext db = new TransactionDBContext();
Guid userID = (Guid)Membership.GetUser().ProviderUserKey;
Query builder:
var transactions = db.Transactions.Where(t => t.UserId == userID);
Or Linq:
var transactions = from transaction in db.Transactions
where transaction.UserId == userID
select transaction;
Edit:
Do you want to always get the data filtered by userId without having to do where clauses in every place?
Your best bet in this case is to create a method in the model to retrieve this data for you:
// In your model code
public IQueryable<Transaction> FromCurrentUser()
{
Guid userID = (Guid)Membership.GetUser().ProviderUserKey;
return db.Transactions.Where(t => t.UserId == userID);
}
In your "Transactions" list page, just limit the transactions by the UserId.
public ActionResult List() {
using (var db = new TransactionDBContext()) {
var results = db.Transactions.Where(x => x.UserID == (Guid)Membership.GetUser().ProviderUserKey).ToList();
return View(results);
}
}