Get Identity value from DataBase on Object creation - c#

I' running a ASP.Net MVC 3 application on Azure. I simply create some users with name and add them in the SQLAzure DB.
Is it possible to get the id of the user on creation or do I need to make a request to the DB.
I actually have:
User user = new User(name);
db.Users.Add(user);
db.SaveChanges();
//Here get the user db generated id
Thanks a lot.

Not sure if it is the same in Azure but when using the entity framework all you have to do to access the ID is user.UserID (or whatever the name of the property is from your db) right after the SaveChanges() call.

Related

Get a value from the database authentication with a custom context

I am trying to recover the value of the user who is logged on the site but I am currently blocked.
I use .Net core 2.1 with EF Core. I created a context called jakformulaireContext and also jakformulaireUser.
I have to send an email to confirm that a user has registered to an event but I can not find the piece of code allowing me to recover the field "email" which is in the database.
In the scaffolding part which contains the Register controller I succeeded because I would recover the value of the field "email" but here I am in a controller that is located outside of Account.
So I tried to do a find but it does not seem to be the right method because I get a Task <> while I just want a string.
var user = _userManager.FindByEmailAsync ("jon#live.be");
Would you have a solution?
If you have an async method it will return a Task. So what you need to do is wait until that method is finished. The way to do it is:
var user = await _userManager.FindByEmailAsync ("jon#live.be");
More information about async/wait

Attempting to create ASP.Net Core Identity data in an existing table with existing user records

I have a new ASP.Net Core website that uses an existing database, to which
I have added ASP.Net Core Identity for user management.
Since there is an existing user table, I simply added the which I have properly added the ASP.Net identity columns.
The additional columns in the existing table are in my IdentityUser-derived class. The site logic works well when I create new users, as well as logging in, logging out, and the like.
The problem is that all of the existing 'user' records (which I will call MyUser) have blank Core Identity fields, and thus are invisible to the identity system calls.
I would like to write a utility that goes through the existing MyUser records, and if the AspIdentityId field is null, set it up as a record manageable by the Identity subsystem.
I'm essentially looking for the 'Create' call, but I can't use UserManager.
CreateAsync because this creates a new record in the table, it doesn't update an existing one.
I do have two DB contexts (IdentityDBContext and OriginalDBContext), so if there is something that allows me to generate the field data, I can then add this to the columns in the table for the associated record.
Ok, I got this to work, not entirely sure why it works, seems like the AspIdentity fields are populated before they are committed. I have only added the specific changes that were the crux of the question, the DI, setup of the contexts, etc are elsewhere in the project.
Essentially, for each 'domain' record, I create a new ApplicationUser (IdentityUser-derived) record, and add the values for the custom fields in the domain record into the ApplicationUser record. Once this object is created, it has the necessary Asp.Net Identity fields already populated. I then get those fields and populate them back onto the domain specific record, then I save this. Once that is done, I re-find the record (this may not be necessary), and add the password based on the plain text password already in the domain record.
var clients = new List<Client>(myService.myContext.Clients);
foreach (var client in clients)
{
var user = new ApplicationUser // Derived from IdentityUser
{
UserID = client.UserID,
FirstName = client.FirstName,
LastName = client.LastName,
UserName = client.UserName,
PhoneNumber = client.Phone,
Email = client.Email // Other fields omitted for brevity.
};
var idUser = user as IdentityUser;
client.AspIdentityId = user.Id;
client.ConcurrencyStamp = user.ConcurrencyStamp;
client.NormalizedEmail = user.NormalizedEmail;
client.NormalizedUserName = user.NormalizedUserName;
client.PasswordHash = user.PasswordHash;
client.SecurityStamp = user.SecurityStamp;
myService.myContext.SaveChanges();
// Can we just use the 'user' object here?
var newUser = await myService.UserManager.FindByIdAsync(client.AspIdentityId);
var result = await myService.UserManager.AddPasswordAsync(newUser, client.Password);
}
Hope this helps someone, this was important to me to get done this way.

ASP.NET Entity Framework trying to update single column

I am using ASP.NET Entity Framework and I am trying to update a single column with the following code:
[HttpGet]
public void MarkOffline(string online)
{
Users user = new Users { email = online, isOnline = false };
db.Entry(user).Property("isOnline").IsModified = true;
db.SaveChanges();
}
But I get this error:
Member 'IsModified' cannot be called for property 'isOnline' because
the entity of type 'Users' does not exist in the context. To add an
entity to the context call the Add or Attach method of DbSet<Users>.
The part I don't know how to do:
To add an entity to the context call the Add or Attach method of
DbSet<Users>.
How do I fix my problem?
If you want to update like this, you'll need to Attach the entity where the entity has its primary key set.
Given you don't have its primary key but only one of its (unique, hopefully) fields, you need to query the record first and then update it:
var existing = db.Users.FirstOrDefault(u => u.email == email);
existing.IsOnline = true;
db.SaveChanges();
That being said, this is not how you record a user's online status in a web application. You rather update a user's LastAction timestamp with each action they perform, and mark a user as offline at runtime when their LastAction is more than N seconds or minutes ago.

how to get the user id of the creator of a reference asp.net mvc

I am wondering how can I get the userID of the user that is logged in, fill the form and post it, ie the creator of a reference of my model Client ?
I need it then to retrieve the last record by the user that have push the reference in the database.
I want to know if there is a method to get the userId of the user that create a reference of my model Client in the create view page ?
Thank you in advance for your help.
If you have logged in user i don't see the problem..Just call
Membership.GetUser().ProviderUserKey

How do you obtain user profile values in ASP.NET Identity 2 of current user?

In an MVC5 application how do you get values from the AspNetUsers table for the current user?
For example: one of the default fileds is PhoneNumber. How do you get the phonenumber of the current logged in user?
I am using Identity 2...
You need to get the IdentityUser object (probably a descendant like ApplicationUser in your application) from Entity Framework. There are a number of ways you could do this, depending on where you are and so on. But, for example, if you wanted to do that in the controller, where you have access to the currently logged in user with the User property, you could use UserManager<TUser>.FindById() like this:
// UserManager here is an instance of UserManager<ApplicationUser>
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
var number = user.PhoneNumber;

Categories

Resources