Can ApplicationDbContext.DbSet<Class> be changed on another page and how can I save it separately?

Volk Volk 551 Reputation points
2023-12-22T12:09:49.61+00:00

Hi!

I. Let's say I have a controller that has a method that gets some model from the database.

METHOD A

var products = await _db.Products.Where(c =>).ToListAsync();
Product p = products[0]; 

It has a text description in p.description.

In this method, I make it empty and send it in a model to the view.

p.description = "";

ATTENTION! I'm not doing here:

_db here.SaveChangesAsync();

The page opens - everything is fine!

Model m = new Model();

m.product = p;

return View(m);

But, then the client goes to a page in the browser where METHOD B is called, which does so without var products = await _db.Products:

METHOD B

_db.SaveChangesAsync();

Question: will p.description = "" be saved as an empty string, or will what was originally there?

**

II.** Is it possible to save ApplicationDbContext not all for all, but separately for some table?

n ot this way:** _db.SaveChangesAsync();

like this: _db.Table123_SaveChangesAsync();

Thanks!

Developer technologies | ASP.NET | ASP.NET Core
{count} votes

Answer accepted by question author
  1. José Pablo Ramirez (a. k. a. webJose) 430 Reputation points Moderator
    2024-01-06T17:57:39.98+00:00

    Ah, the intricacies of Entity Framework. If I understood correctly, you ave a model XX with property Description. Model XX is available to many users, but only some users should be able to access XX.Description, so you blank it out in MethodA for people without access. MethodA is not shown in the question, but from context I am concluding that MethodA returns a view capable of editing the object. When the view posts, it posts to MethodB, in charge of saving updates. You want to make sure the XX.Description remains intact if the user was an underprivileged user.

    If my understanding is correct, the simplest way would be to have a MethodBPrivileged and a regular MethodB, where the former will update XX.Description, but the latter won't.

    In Entity Framework jargon... I'm unsure as I avoid it like the plague. Can EF map 2 models to the same table? If it can, create 2 models: One that contains the Description property, and one that doesn't. Then, in the server's MethodA routine, by virtue of checking the logged-in privileges, determine which model to use and which view to send: A view that posts to MethodB, or a view that posts to MethodBPrivileged.

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.