I would like to call a Create View from the "Buchungen" controller.
To do this, I would like to add some data from another table (ArWoo) to the view so that it is already filled out in advance.
The two tables are not linked.
I give the appropriate ID when calling the "Buchungen" controller.
// GET: Buchungen/Create_AR
public IActionResult Create_AR(int? id)
{
var AR = _context.ArWoo
.Where(n => n.Id == id);
ViewData["Bestellnummer"] = AR.Bestellnummer;
return View("Create");
}
How can I now transfer a value from AR (e.g. "Bestellnummer") to the view?
I thought that would just go along with ViewData["Bestellnummer"] = AR.Bestellnummer;
But this doesn´t work.
If I set a breakpoint at return View ("Create"), I see that the variable AR is correctly assigned.enter image description here
Fix the action by adding FirstOrdefault to a query
public IActionResult Create_AR(int? id)
{
var AR = _context.ArWoo
.Where(n => n.Id == id).FirstOrDefault();
ViewData["Bestellnummer"] = AR.Bestellnummer;
// or return View("Create",AR.Bestellnummer);
return View("Create");
}
Related
So I have a search-input and checkboxes that passes the values to the controller when there are inputs. And I want to use these values to get something back from the database. The search-input is a string and it works and intended. Here is the code for the search-input:
public async Task<ViewResult> Index(string searchString, List<int> checkedTypes)
{
var products = from p in _db.Products select p;
ViewData["CurrentFilter"] = searchString;
if (!string.IsNullOrEmpty(searchString))
{
products = products.Where(p => p.Name.ToLower().Contains(searchString));
}
return View(products);
}
However the checkboxes values are stored in a list. So basically I want to do the same as the code above, but with a list. So basically an idea is like this:
if(checkedTypes != null)
{
foreach (var i in checkedTypes)
{
products = products.Where(p => p.TypeId == i));
}
}
If I do it like the code above, I just get the last (i) from the loop. Another solution I did was this:
if(checkedTypes != null)
{
var temp = new List<Product>();
foreach (var i in checkedTypes)
{
temp.AddRange(products.Where(p => p.TypeId == i));
}
products = temp.AsQueryable();
}
But when I did it like that I get this error:
InvalidOperationException: The provider for the source IQueryable doesn't implement IAsyncQueryProvider. Only providers that implement IAsyncQueryProvider can be used for Entity Framework asynchronous operations.
So anyone have a solution that I can use? Or is there a better way to handle checkboxes in the controller?
Assuming you are using EF Core (also the same is true for linq2db) - it supports translating filtering with local collection, i.e. Where(x => checkedTypes.Contains(x.SomeId)).
If you have "and" logic to filter by searchString and checkedTypes than you can conditionally add Where clause:
if (!string.IsNullOrEmpty(searchString))
{
products = products.Where(p => p.Name.ToLower().Contains(searchString));
}
if(checkedTypes != null)
{
products = products.Where(p => checkedTypes.Contains(p.TypeId));
}
P.S.
Also you should be able to change your first line to:
var products = _db.Products.AsQueryable();
I have a table named dbo.EmployeeType with three records:
PK_EmployeetypeID EmployeeTypeName
1 Project Manager
2 Business Analyst
3 Developer
I have this piece of Linq code:
public static string GetTypeByID(int id)
{
using (ProjectTrackingEntities1 db = new ProjectTrackingEntities1())
{
var type = db.EmployeeTypes.Select(o => new LOOKUPEmployeeType
{
PK_EmployeeTypeID = id,
EmployeeTypeName = o.EmployeeTypeName
});
return type.FirstOrDefault().EmployeeTypeName;
}
}
No matter what id I send to it, it returns Project Manager, and I'm confused as to why.
You need to apply a filter, otherwise you're just returning the first record and hard coding the ID. Try this:
public static string GetTypeByID(int id)
{
using (ProjectTrackingEntities1 db = new ProjectTrackingEntities1())
{
//Here we apply a filter, the lambda here is what creates the WHERE clause
var type = db.EmployeeTypes
.FirstOrDefault(et => et.PK_EmployeeTypeID == id);
if(type != null)
{
return type.EmployeeTypeName;
}
else
{
return "";
}
}
}
Note that using FirstOrDefault means if there are no matches, or multiple matches, type will be null and you will get an empty string returned.
Set a breakpoint on type = ... and inspect it. You have no Where in there so you get all - and Select just makes LOOKUPEmployeeTypes out of all of them.
FirstOrDefault then returns the first of those 3 which is always the ProjManager
Fix:
var type = db
.EmployeeTypes
.Where( o => o.Id == id)
.Select(o => new LOOKUPEmployeeType
{
PK_EmployeeTypeID = id,
EmployeeTypeName = o.EmployeeTypeName
});
In your code you only return the first value. You need to tell EF which value you need to return.
Let us assume you need the value with Id=2. Instead of Select(), use Single(x => x.Id == 2) or First(x => x.Id == 2).
I need to update a second table in my EF, this table is my storage of purchase, i call this entity and search the value for change (Qty), i do the math comparasion and send back the data updated, but raise a error tell me "An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key"
How fix the error? Thanks
My Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(PurchaseDetails purchasedetails)
{
ViewBag.PurchaseID = new SelectList(db.Purchases, "PurchaseID", "Notes", purchasedetails.PurchaseID);
ViewBag.idArt = new SelectList(db.Art, "idArt", "des_art", purchasedetails.IdArt);
ViewBag.idAlmacen = new SelectList(db.Almacens, "idAlmacen", "des_alma", purchasedetails.IdAlmacen);
var cant_details = db.PurchaseDetails.Where(p => p.PurchaseDetailsID == purchasedetails.PurchaseDetailsID).FirstOrDefault();
var cantidad = purchasedetails.Qty - cant_details.Qty;
if (ModelState.IsValid)
{
db.Entry(purchasedetails).State = EntityState.Modified;
db.SaveChanges();
var stock_id = db.Stock.Where(s => s.idAlmacen == purchasedetails.IdAlmacen && s.idArt == purchasedetails.IdArt).FirstOrDefault();
stock_id.stcActual = stock_id.stcActual + cantidad;
db.Stock.Attach(stock_id);
var entry = db.Entry(stock_id);
entry.Property(e => e.stcActual).IsModified = true;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(purchasedetails);
}
I found The solution in this post
How do I detach objects in Entity Framework Code First?
i used AsNoTracking() in my line code
var cant_details = db.PurchaseDetails.Where(p => p.PurchaseDetailsID == purchasedetails.PurchaseDetailsID).FirstOrDefault();
and work perfectly
var cant_details = db.PurchaseDetails.AsNoTracking().Where(p => p.PurchaseDetailsID == purchasedetails.PurchaseDetailsID).FirstOrDefault();
I have a parameter that is passed to a action from a view that when matched only shows those corresponding results.
Everything works as normal when the parameter passed in has a match, but when the id being passed it does not match any id, the corresponding view is showing all the results.
public ActionResult ShowResults(Guid ParameterId)
{
return this.PartialView(this.MyClassVariable.MyGetMStuffMetod().Where(x => x.Id == ParameterId));
}
Is there a way I can tell it if the ids do not match return nothing?
My Method
public IList<MyStuffViewModel> MyGetStuffMethod()
{
IList<MyStuffViewModel> result = (IList<MyStuffViewModel>)HttpContext.Current.Session["MyStuff"];
if (result == null)
{
HttpContext.Current.Session["MyStuff"] = result =
(from mStuff in new dbEntities().TableA
select new MyStuffViewModel
{
Id = mStuff.Id,
Name = mStuff.Name
}).ToList();
}
return result;
}
This worked, but I think it is something else causing the issue, I will track it down and post the results. Thanks for the help.
.Where(x => x.Id == ParameterId).GroupBy(t => t.ParameterId));
the for each loop works properly setting the PickupDistanceSort column correctly, but then I can't get the model to sort so that I can display the rows in ascending order based on the newly set PickupDistanceSort values. PickupDistanceSort is a data type of long. The model displays in the view, it's just not sorted. How do you sort a model before it's sent to the view?
public ActionResult JobsDistanceSorted()
{
var model = from j in db.Jobs select j;
foreach (var item in model)
{
item.PickupDistanceSort = ICN.CustomMethods.
GetDistance(34.180046081543, -118.309028625488,
item.PickupLatitude, item.PickupLongitude);
}
model = model.OrderBy(s => s.PickupDistanceSort);
return View("JobHeadings", model);
}
You have to convert it to List which stores items locally, and then you can call OrderBy on local list. Calling OrderBy on IQueryable will result in new database query, in which the values are not stored.
public ActionResult JobsDistanceSorted()
{
var model = db.Jobs.ToList();
foreach (var item in model)
{
item.PickupDistanceSort = ICN.CustomMethods.
GetDistance(34.180046081543, -118.309028625488,
item.PickupLatitude, item.PickupLongitude);
}
return View("JobHeadings", model.OrderBy(s => s.PickupDistanceSort));
}
If PickupDistanceSort is not a .Net type you need to imlement an IEqualityComparer for your type and use OrderBy like this (PickupDistanceComparer is the name of your custom comparer):
model = mode.OrderBy(s => s.PicupDistanceSort, new PickupDistanceComparer());