I need to write this SQL statement in Entity Framework:
SELECT
SALARIE.MATRICULE, LIEU, UO, UO_RATTACHEMENT,
PHOTO.PHOTO, SALARIE.NOM, SALARIE.PRENOM
FROM
SALARIE, UNITE_ORG, PHOTO
WHERE
SALARIE.LIEU = UNITE_ORG.UO
I use this method for reading my data :
public JsonResult Read()
{
var nodes = entities.UNITE_ORG.Select(p => new NodeModel { id = p.UO, pid = p.UO_RATTACHEMENT, poste = p.POSTE, img=p.LIB_COMPLET, Fullname=p.RESPONSABLE });
return Json(new { nodes = nodes }, JsonRequestBehavior.AllowGet);
}
I need to change this declaration of nodes.
Thank you
I believe that the equivalent Entity Framework would be the following:
var result = (from s in context.SALARIE
from u in context.UNITE_ORG
from p in context.PHOTO
where s.LIEU == u.UO
select new {
MATRICULE = s.MATRICULE,
LIEU = s.LIEU,
UO = u.UO,
UO_RATTACHEMENT = UO_RATTACHEMENT, // I don't know where this is coming from
PHOTO = p.PHOTO,
NOM = s.NOM,
PRENOM = s.PRENOM
}
);
However, this is just a guess from the information you have giving.
Also, like I have stated in my comment, I really think you should stop using the syntax for cross joins that you are doing (the , seperated syntax)
Related
I'm trying to update two entities at the same time but the change is not applying and I think that when I try to return the update entity it doesn't even found it.
Here is my Razor view:
public IActionResult OnPost()
{
if (!ModelState.IsValid)
{
return Page();
}
repositorioFamiliar.Actualizar(Familiar);
return RedirectToPage("/Familiares/DetalleFamiliar", new { IdPaciente = Familiar.IdPaciente });
}
Here is my update function:
public FamiliaresPer Actualizar(FamiliaresPer familiar)
{
var familiarActualizar = (from f in _context.Familiars.Where(p => p.IdFamiliar == familiar.IdFamiliar) select f).FirstOrDefault();
if (familiarActualizar != null)
{
familiarActualizar.Correo = familiar.Correo;
_context.Update(familiarActualizar);
_context.SaveChanges();
}
var personaActualizar = (from p in _context.Personas.Where(p => p.Id == familiar.IdPersona) select p).FirstOrDefault();
if (personaActualizar != null)
{
personaActualizar.Telefono = familiar.Telefono;
_context.Update(personaActualizar);
_context.SaveChanges();
}
var familiares = from p in _context.Familiars
from p1 in _context.Personas
where p.IdPaciente == familiar.IdPaciente
where p.IdPersona == p1.IdPersona
select new FamiliaresPer()
{
IdFamiliar = p.IdFamiliar,
IdPaciente = p.IdPaciente,
IdPersona = p1.IdPersona,
Id = p1.Id,
Nombres = p1.Nombres,
Apellidos = p1.Apellidos,
Genero = p1.Genero,
Telefono = p1.Telefono,
Parentesco = p.Parentesco,
Correo = p.Correo,
};
FamiliaresPer familiaresPer = familiares.FirstOrDefault();
return familiaresPer;
}
When I submit the form I get an error
NullReferenceException: Object reference not set to an instance of an object
And the link shows the IdPaciente = 0 when it should use the same IdPaciente of the updated entity (which the Id never changes).
In your OnPost( ) Action Method, you used repositorioFamiliar.Actualizar(Familiar);
but it looks like you didn't define 'Familiar'.
In addition, when I look at your code. I can give you an advice. Let's say your first update was done correctly and you got an error in the second update case. But you want both to be updated at the same time. Assume that the first object is updated in the database but the second one isn't. This is a problem, right? Unit of Work design pattern is very useful to solve this.
In brief, The approach should be to do SaveChanges() after both update processes are completed so there will be no changes in the database until both updates are completed.
I want to retrieve the specific data using an array-values, but I don't know how to deal with it.
URL is like http://localhost/api/data?sym=aa&bb&cc
DB documents are like:
{"symbol":"aa","price":1.1}
{"symbol":"bb","price":1.2}
{"symbol":"cc","price":1.3}
{"symbol":"dd","price":1.4}
{"symbol":"ee","price":1.5}
the expected result is:
[
{"symbol":"aa","price":1.1}
{"symbol":"bb","price":1.2}
{"symbol":"cc","price":1.3}
]
My code is:
[HttpGet()]
public IEnumerable<Data> Get(string sym)
{
symbol = sym.Split('&');
//connect to database and collections
var client = new MongoClient("mongodb+srv://.....");
var db = client.GetDatabase("...");
var _portf = db.GetCollection<Data>("...");
return _portf.Find(???).ToList();
}
??? is where I have failed to find a solution. or I am completely wrong with the find() method.
I really need your help. Thank you!
Find takes in a FilterDefinition object. For example, a common way of getting a document from MongoDB by its ID would be:
public T LoadRecordById<T>(string table, Guid id)
{
var collection = db.GetCollection<T>(table);
var filter = Builders<T>.Filter.Eq("Id", id);
return collection.Find(filter).First();
}
You can combine multiple FilterDefinition objects together using the Or method:
var filter1 = Builders<T>.Filter.Eq("symbol", symbol);
var filter2 = Builders<T>.Filter.Eq("symbol", symbol);
var filter3 = Builders<T>.Filter.Eq("symbol", symbol);
var filter = Builders<T>.Filter.Or(filter1, filter2, filter3);
Hope this helps (it does not hurt to be nice, does it, #Dharman?)
I've found a very promising way which works perfectly. Thanks to this video
rewrite the code"
[HttpGet()]
public IEnumerable<Data> Get(string sym)
{
var symlist = sym.Split('&');
//connect to database and collections
var client = new MongoClient("mongodb+srv://.....");
var db = client.GetDatabase("...");
var _portf = db.GetCollection<Data>("...");
-->var fitlerDefinition = Builders<Findata>.Filter.In(a => a.Symbol, symlist);
return _portf.Find(fitlerDefinition).ToList();
}
I am working on a asp.net core 1.1 project and i want to create paging in my some views. I studied microsoft documents about paging in asp core but it is very simple mode with 1 table. In my view i use multi table and use a viewmodel to initialize it. I want to use PagingList<T>.CreateAsync() method to create paging but get error:
can not convert from system.linq.Iqueryable<> to system.linq.IorderedQueryable<>
my action:
[HttpGet]
public async Task<IActionResult> Index(int? page)
{
List<BookListViewModel> model = new List<BookListViewModel>();
var query = (from b in _context.books
join a in _context.authors on b.AuthorID equals a.AuthorId
join bg in _context.bookgroups on b.BookGroupID equals bg.BookGroupId
select new
{
b.BookId,
b.BookName,
b.BookPageCount,
b.BookImage,
b.AuthorID,
b.BookGroupID,
a.AuthorName,
bg.BookGroupName
});
foreach (var item in query)
{
BookListViewModel objmodel = new BookListViewModel();
objmodel.BookId = item.BookId;
objmodel.BookName = item.BookName;
objmodel.BookImage = item.BookImage;
objmodel.BookPageCount = item.BookPageCount;
objmodel.AuthorId = item.AuthorID;
objmodel.BookGroupId = item.BookGroupID;
objmodel.AuthorName = item.AuthorName;
objmodel.BookGroupName = item.BookGroupName;
model.Add(objmodel);
}
ViewBag.RootPath = "/upload/thumbnailimage/";
int pageSize = 3;
int pageNumber = (page ?? 1);
return View(await PagingList<BookListViewModel>.CreateAsync(model.AsQueryable() , pageNumber, pageSize));
}
I have not yet written anything about paging in index view and it is a simple list of viewmodel
Well can't really be sure from the code you posted. But the exception says the the CreateAsync method needs IOrderedQueryable, but you're giving it an IQueryable.
Try changing it to pass in the query object (which I guess should implement the IOrderedQueryable, if you're using Entity framework).
The idea behind the PagingList (presumably) is to use it to do the paging in the database.
What you're doing is bringing the filterted set into memory (when for-eaching through the result), and then doing doing the paging.
The code might look something like this:
[HttpGet]
public async Task<IActionResult> Index(int page = 1)
{
var query = (from b in _context.books
join a in _context.authors on b.AuthorID equals a.AuthorId
join bg in _context.bookgroups on b.BookGroupID equals bg.BookGroupId
select new BookListViewModel()
{
BookId = b.BookId,
BookName = b.BookName,
BookPageCount = b.BookPageCount,
BookImage = b.BookImage,
AuthorId = b.AuthorID,
BookGroupId = b.BookGroupID,
AuthorName = a.AuthorName,
BookGroupName = bg.BookGroupName
}).AsNoTracking().OrderBy(u => u.BookId);
ViewBag.RootPath = "/upload/thumbnailimage/";
var pagedResult = await PagingList<BookListViewModel>.CreateAsync(query, 10, page);
return View(pagedResult);
}
Hope it helps.
I am using a database-first approach with a custom html helper to get a state of a checkbox using ajax (without using form in the view). I have two tables:
Tbl_1 -> Id, state (true or false), name (name of checkbox)
Tbl_2 -> Id, user_guid, timestamp, Tbl_1Id (foreign_key)
When I do insert operations, it does without any problem but when I try to update it (based upon the logged in user as it also gets GUID, the table gets appended/inserted with new data).
My controller:
public ActionResult SetState(checkboxstate cbstate)
{
var UserId = new Guid(System.Security.Claims.ClaimsPrincipal.Current.FindFirst("sub").Value);
var ent = new StartopDatabaseEntities();
var cbs = ent.checkboxstates.Where(w => w.Name == "World").FirstOrDefault();
if (cbs == null) // when there are no records in the database
{
ent.checkboxstates.Add(cbstate);
ent.checkboxstateUpdates.SingleOrDefault(c => c.Id == cbstate.Id);
var cbsOp = new checkboxstateUpdates();
cbsOp.timestamp = DateTime.Now;
cbsOp.user_guid = UserId;
cbstate.checkboxstateUpdates.Add(cbsOp);
ent.SaveChanges();
} // record in database, update (I've only one user now, so has to update only this one)
else
{
var cbsOp = new checkboxstateUpdates(); // declare in global
var chc = new checkboxstate(); // to be declared in global
var newCbs = ent.checkboxstateUpdates.Include(c => c.checkboxstate).ToList();
foreach (var u in newCbs)
{
if(u.user_guid==UserId && u.CheckboxStateId == u.checkboxstate.Id)
{
chc.state = cbstate.state;
chc.name = cbstate.name;
ent.checkboxstates.Add(chc);
cbsOp.Tidspunkt = DateTime.Now;
cbsOp.OpdateretAfBruger = UserId;
ent.checkboxstateUpdates.Add(cbsOp);
ent.SaveChanges();
}
}
}
Can anyone explain please why it's not updating but appending/inserting same data with a new Id (primary key)? I have a simple view where Ajax sends a call to the controller with the state and name of the checkbox. I have also tried
Db.Entry(obj).state = EntityState.Modified
without any help
You have not written the code for the logic which want to achieve..
I am not clear on the logic of if block also but the else part can be fixed as following.
var newCbs = ent.checkboxstateUpdates.Include(c => c.checkboxstate).Where(u.user_guid == UserId).FirstOrDefault();
if(newCbs != null) {
newCbs.checkboxstate.state = cbstate.state;
newCbs.checkboxstate.name = cbstate.name;
newCbs.Tidspunkt = DateTime.Now;
newCbs.OpdateretAfBruger = UserId;
ent.SaveChanges();
}
Solved this with the help from #David & #Chetan:
I did some modify in the code as per David:
u.checkboxstate.state=cbstate.state;
u.checkboxstate.name=cbstate.name;
u.timestamp=DateTime.Now;
ent.saveChanges();
I was using the wrong logic i.e. getting instance of the class rather than the 'ent' object. Thanks guys for the help.
The following query is working successfully.
var tabs = (
from r in db.TabMasters
orderby r.colID
select new { r.colID, r.FirstName, r.LastName })
.Skip(rows * (page - 1)).Take(rows);
Now I want to return JsonResult as like
var jsonData = new
{
total = (int)Math.Ceiling((float)totalRecords / (float)rows),
page = page,
records = totalRecords,
rows = (from r in tabs
select new { id = r.colID, cell = new string[] { r.FirstName, r.LastName } }).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
But it will gives me an error like:
The array type 'System.String[]' cannot be initialized in a query result. Consider using 'System.Collections.Generic.List`1[System.String]' instead.
What should I do to get expected result?
I suspect that it's as simple as pushing the last part into an in-process query using AsEnumerable():
var jsonData = new
{
total = (int)Math.Ceiling((float)totalRecords / (float)rows),
page = page,
records = totalRecords,
rows = (from r in tabs.AsEnumerable()
select new { id = r.colID,
cell = new[] { r.FirstName, r.LastName } }
).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
You may want to pull that query out of the anonymous type initializer, for clarity:
var rows = tabs.AsEnumerable()
.Select(r => new { id = r.colID,
cell = new[] { r.FirstName, r.LastName })
.ToArray();
var jsonData = new {
total = (int)Math.Ceiling((float)totalRecords / (float)rows),
page,
records = totalRecords,
rows
};
It's because it's adding to the LINQ query that is your tabs IQueryable. That is then trying to turn the LINQ expression into a SQL query and the provider doesn't support projecting arrays.
You can either change the assignment of the tabs variable's LINQ expression to use ToList to materialize the DB results right then and there, or you can add .AsEnumerable() to the LINQ expression assigned to the rows field of the anonymous type that is your JsonResult. AsEnumerable will demote the IQueryable to an IEnumerable which will prevent your second LINQ query from trying to be added to the DB query and just make it a LINQ-to-objects call like it needs to be.