concatenate strings in LINQ query - entity-framework

Suppose I want to set FullName property using string.Format like this:
var userList = users.Select(user => new User()
{
Id = user.Id,
UserName = user.UserName,
FirstName = user.FirstName,
LastName = user.LastName
FullName = string.Format("{0} {1}", user.UserName, user.FirstName)
}).ToList();
This obviously doesn't work because LINQ doesn't know about string.Format.
My question is what are the other options beside going over the list in memory and setting FullName for each item?
userList.ForEach(u => u.FullName = string.Format("{0} {1}", user.UserName, user.FirstName))
UPDATE: to see what I need, please see my conversation with #octavioccl below

you can use it:
FullName = user.UserName + " " + user.FirstName
But I think that it could be better solution (of cource if it's possible for you):
public class User
{
public int Id {get;set;}
public string UserName {get;set;}
public string FirstName {get;set;}
public string LastName {get;set;}
public string FullName
{
get
{
return string.Format("{0} {1}", FirstName, LastName);
}
}
}
then in your query build it:
var userList = users.Select(user => new User()
{
Id = user.Id,
UserName = user.UserName,
FirstName = user.FirstName,
LastName = user.LastName
}).ToList();

String.Format is not supported in EF, try this way:
FullName = user.UserName + " " + user.FirstName
In this link you will find all CLR methods that are supported

Another object is to project to an anonymous type without that property, then project to the final type in linq-to-objects:
var userList = users.Select(user => new {
Id = user.Id,
UserName = user.UserName,
FirstName = user.FirstName,
LastName = user.LastName
})
.AsEnumerable()
.Select(user => new User()
{
Id = user.Id,
UserName = user.UserName,
FirstName = user.FirstName,
LastName = user.LastName
FullName = string.Format("{0} {1}", user.UserName, user.FirstName)
})
.ToList();

Related

Salesforce Test class getting System.JSONException: Malformed JSON: Expected '[' at the beginning of List/Set Error

I have written a trigger and handler class (which uses a future method) and it works well. I am really struggling to write the test class for it. My first problem is that the code coverage is high (before tweaks it was 0% in the handler class). After tweaking, I am getting the following error:
System.JSONException: Malformed JSON: Expected '[' at the beginning of List/Set
I am not sure how to solve this and I am a pretty new dev so not sure what to do next . Can someone please help?
Here is my code:
Trigger:
trigger AccountTriggerKeepAcctTeam on Account (before update) {
List<AccountTeamMember> listAcc = [SELECT Id, AccountAccessLevel, AccountId, CaseAccessLevel, UserId, ContactAccessLevel, OpportunityAccessLevel, TeamMemberRole, PhotoUrl, Title FROM AccountTeamMember Where AccountId in : Trigger.new AND TeamMemberRole != 'Account Executive'];
for(Account acc: Trigger.new){
Account oldAccount = Trigger.oldMap.get(acc.Id);
if(acc.OwnerId != oldAccount.OwnerId){
system.debug('AccountTeamMember records: '+(JSON.serialize(listAcc)));
String str = JSON.serialize(listAcc);
//delete team member records if required
AccountTriggerKeepAcctTeamHandler.retainOldTeamMemberOnOwnerChange(str);
}
}
}
Handler:
public class AccountTriggerKeepAcctTeamHandler {
#future
public static void retainOldTeamMemberOnOwnerChange(String str){
system.debug('Future call '+str);
List<AccountTeamMember> newlistAcc = (List<AccountTeamMember>) JSON.deserialize(str,List<AccountTeamMember>.class);
for(AccountTeamMember objAccTeamMember : newlistAcc){
objAccTeamMember.Id= null;
}
system.debug('Account records to insert'+(JSON.serialize(newlistAcc)));
Upsert newlistAcc;
}
}
Test class:
#isTest
public class AccountTriggerKeepAcctTeamTest {
//#TestSetup
static testMethod void AcctOwnerChange(){
List<User> userList = TestDataFactory.createUser(true, 2);
Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator'];
User u1 = new User(Alias = 'standt', Email='standarduser#testorg1.com',
EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
LocaleSidKey='en_US', ProfileId = p.Id,
TimeZoneSidKey='America/Los_Angeles', UserName='standarduser#testorg01.com');
insert u1;
User u2 = new User(Alias = 'standt', Email='standarduser#testorg2.com',
EmailEncodingKey='UTF-8', LastName='Testing2', LanguageLocaleKey='en_US',
LocaleSidKey='en_US', ProfileId = p.Id,
TimeZoneSidKey='America/Los_Angeles', UserName='standarduser#testorg92.com');
insert u2;
System.runAs(u1){
Allowed_Account_Owner_Change__c setting = new Allowed_Account_Owner_Change__c();
setting.Allowed_to_change_Account_Owner__c = true;
insert setting;
fferpcore__ExchangeRateGroup__c exrg = new fferpcore__ExchangeRateGroup__c(CurrencyISOCode = 'USD', fferpcore__DefaultCurrency__c = 'USD - U.S. Dollar', Name = 'FF Shared Test Group', fferpcore__SelectedCurrencies__c = 'USD - U.S. Dollar');
insert exrg;
c2g__codaCompany__c company = new c2g__codaCompany__c();
company.Name = 'ApexTestCompany';
company.RecordTypeId = Schema.SObjectType.c2g__codaCompany__c.RecordTypeInfosByName.get('SUT').RecordTypeId;
insert company;
company.c2g__ExchangeRateGroup__c = exrg.Id;
update company;
Account acc = new Account(Name = 'Test Acc2', NumberOfEmployees = 500);//TestDataFactory.createAccountwithCurrencyMaster(true);
acc.OwnerId = userinfo.getUserId();
insert acc;
AccountTeamMember accTeam = new AccountTeamMember();
accTeam.UserId = acc.OwnerId;
accTeam.AccountAccessLevel = 'Read';
accTeam.AccountId = acc.Id;
insert accTeam;
System.debug('## User '+userinfo.getUserName());
//create opportunity
//}
// }
// static testMethod void testAcctOwnerChange(){
// User u = [Select id, LastName from User where LastName = 'Testing2'];
// Account acc = [Select id, OwnerId from Account Limit 1];
Test.startTest();
acc.OwnerId = u2.id;
update acc;
AccountTriggerKeepAcctTeamHandler.retainOldTeamMemberOnOwnerChange(JSON.serialize(acc));
//System.assertEquals(accTeam.UserId,u2.Id);
Test.stopTest();
//AccountTeamMember atm = [Select userId,AccountId, AccountAccessLevel from AccountTeamMember where AccountId =: acc.Id];
}
}
Can someone please help? I am a beginner apex dev
Trigger Attempt for Alin's test class:
trigger AccountTriggerKeepAcctTeam on Account (before update) {
Set<Id> accteammbrId = new Set<Id>();
List<AccountTeamMember> listAcc = [SELECT Id, AccountAccessLevel, AccountId, CaseAccessLevel, UserId, ContactAccessLevel, OpportunityAccessLevel, TeamMemberRole, PhotoUrl, Title FROM AccountTeamMember Where AccountId in : Trigger.new AND TeamMemberRole != 'Account Executive'];
for(Account acc: Trigger.new){
Account oldAccount = Trigger.oldMap.get(acc.Id);
if(acc.OwnerId != oldAccount.OwnerId){
//system.debug('AccountTeamMember records: '+(JSON.serialize(listAcc)));
//String str = JSON.serialize(listAcc);
for(AccountTeamMember actmbr : listAcc){
accteammbrId.add(actmbr.Id);
}
//delete team member records if required
AccountTriggerKeepAcctTeamHandler.retainOldTeamMemberOnOwnerChange(accteammbrId);
}
}
}
public class AccountTriggerKeepAcctTeamHandler {
#future
public static void retainOldTeamMemberOnOwnerChange(Set<Id> AccteambrId){
List<AccountTeamMember> newlistAcc = [SELECT Id, AccountAccessLevel, AccountId, CaseAccessLevel, UserId, ContactAccessLevel, OpportunityAccessLevel, TeamMemberRole, PhotoUrl, Title FROM AccountTeamMember Where AccountId in :AccteambrId];
//system.debug('Future call '+str);
//List<AccountTeamMember> newlistAcc = (List<AccountTeamMember>) JSON.deserialize(str,List<AccountTeamMember>.class);
for(AccountTeamMember objAccTeamMember : newlistAcc){
objAccTeamMember.Id= null;
}
//system.debug('Account records to insert'+(JSON.serialize(newlistAcc)));
system.debug('Account records to insert' + newlistAcc);
Upsert newlistAcc;
}
}
I don't understand why you have to serialize the list in the first place.
Change your retainOldTeamMemberOnOwnerChange to accept a List as parameter and don't use the JSON at all.
Then in your test class you create an account, assign an account team to it and change the owner. After that you will query the List of associated AccountTeamMember and assert it with regards to the AccountTeamMember before the ownership of the account was changed.
If it's not clear enough I can give you a code example, but I think the exercise will be good for you.
Edit: I see. My bad. This is what I use for test coverage. I can also provide code sample from the trigger if needed.
Trigger:
trigger AccountTrigger on Account (before update, After Update) {
if(trigger.isBefore){
if(trigger.isUpdate){
AccountTriggerHandler.retainAccountTeam(trigger.new, trigger.oldMap);
}
}
}
Handler:
public class AccountTriggerHandler {
public static void retainAccountTeam(List<Account> newList, Map<Id, Account> oldMap) {
Set<Id> accountsWithNewOwners = new Set<Id>();
for(Account acc : newList){
if(acc.OwnerId != oldMap.get(acc.Id).OwnerId){
accountsWithNewOwners.add(acc.Id);
}
}
if(accountsWithNewOwners.size() > 0){
List<AccountTeamMember> listAcc = [SELECT Id, AccountAccessLevel, AccountId, CaseAccessLevel, UserId, ContactAccessLevel, OpportunityAccessLevel, TeamMemberRole, PhotoUrl, Title FROM AccountTeamMember WHERE AccountId IN :accountsWithNewOwners];
system.debug('AccountTeamMember records: '+(JSON.serialize(listAcc)));
String str = JSON.serialize(listAcc);
// delete team member records if required
retainOldTeamMemberOnOwnerChange(str);
}
}
//Before Update calls the future method that basically reinserts the Account Team member records. You can also consider deleting the Account Team Member records before calling the future method.
#future
public static void retainOldTeamMemberOnOwnerChange(String str){
system.debug('Future call '+str);
List<AccountTeamMember> newlistAcc = (List<AccountTeamMember>) JSON.deserialize(str,List<AccountTeamMember>.class);
for(AccountTeamMember objAccTeamMember : newlistAcc){
objAccTeamMember.Id= null;
}
system.debug('Account records to insert'+(JSON.serialize(newlistAcc)));
Upsert newlistAcc;
}
}
Test method:
static testMethod void test_retainAccountTeam(){
Id mhbkRTId = Schema.SObjectType.Account.getRecordTypeInfosByName().get('MHBK').getRecordTypeId();
Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator'];
User u = new User(
Alias = 'rivacon',
Email = 'rivaConnector#testorg.com',
EmailEncodingKey = 'UTF-8',
LastName = 'Connector',
FirstName = 'Riva',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
ProfileId = p.Id,
TimeZoneSidKey = 'America/Los_Angeles',
UserName = 'rivaConnector#testorg.com');
insert u;
User u2 = new User(
Alias = 'updated',
Email = 'rivaConnector#testorg.com',
EmailEncodingKey = 'UTF-8',
LastName = 'Connector',
FirstName = 'Riva2',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
ProfileId = p.Id,
TimeZoneSidKey = 'America/Los_Angeles',
UserName = 'rivaConnector2#testorg.com');
insert u2;
system.runAs(u){
Account acc = new Account(RecordTypeId = mhbkRTId,Name = 'test',Branch__c='London',Industry='Banking',Year_Founded__c='1900',BillingStreet = '1 Long Rd',BillingCity = 'City',CurrencyIsoCode = 'GBP');
insert acc;
AccountTeamMember atm = new AccountTeamMember();
atm.AccountId = acc.Id;
//atm.Name ='Test ATM';
atm.TeamMemberRole = 'Sales Assistant';
atm.UserId = u.Id;
insert atm;
Test.startTest();
acc.OwnerId = u2.Id;
update acc;
Test.stopTest();
System.debug('usr1 ' + u.id);
System.debug('usr2 ' + u2.id);
Account updatedAccount = [SELECT OwnerId FROM Account WHERE Id = :acc.Id];
system.assertEquals(u2.Id, updatedAccount.OwnerId);
List<AccountTeamMember> teamMembers = [SELECT Id, AccountAccessLevel, AccountId, UserId, TeamMemberRole, Title FROM AccountTeamMember WHERE AccountId = :acc.Id];
system.assertEquals(1, teamMembers.size());
system.assertEquals(teamMembers[0].TeamMemberRole, atm.TeamMemberRole);
}

Dynamic list using array from anthor list

My application is ASP.NET MVC 5 / SQL Server.
I am trying to select specific columns from a list based on an array:
First list has 200 columns: Age, Gender, .....
var list1 = _reportRepository.ShowMasteView().ToList();
Second list has 20 columns: Age, Gender, ......
From the view I select the items to be displayed:
string[] lits2 = showColumn.Where(c => c.Value == true).Select(c=> c.Key).ToArray();
I get
To get these two specific columns, I tried
var nList = list1.Select(t2 => lits2.Any(t1 => t2.Contains(t1)));
I get an error
Can not resolve symbol "Contains"
I was able to do it using the following
var keys = "Age,Gender";
var connection =
ConfigurationManager.ConnectionStrings["DALEntities"].ConnectionString;
using (var dataAdapter = new SqlDataAdapter("SELECT " + keys
+ " from dbo.vw_MasterView", connection))
{
var dataTable = new DataTable();
dataAdapter.Fill(dataTable);
dataAdapter.FillSchema(dataTable, SchemaType.Mapped);
return dataTable;
}
Is there a better way in linq?
From my understand it appears you are trying to extract/select a dynamic object that only has the desired properties/columns.
This can be achieved by building a dynamic expression/function to apply to the Select
The following builds an expression based on the model type and the provided properties
static class DynamicExtensions {
public static IQueryable<dynamic> SelectDynamic<TModel>(this IQueryable<TModel> query, ISet<string> propertyNames) {
var selector = query.BuildSelectorFor(propertyNames);
return query.Select(selector);
}
static Expression<Func<TModel, dynamic>> BuildSelectorFor<TModel>(this IQueryable<TModel> query, ISet<string> propertyNames) {
var modelType = typeof(TModel);
var properties = modelType.GetProperties().Where(p => propertyNames.Contains(p.Name));
// Manually build the expression tree for
// the lambda expression v => new { PropertyName = v.PropertyName, ... }
// (TModel v) =>
var parameter = Expression.Parameter(modelType, "v");
// v.PropertyName
var members = properties.Select(p => Expression.PropertyOrField(parameter, p.Name));
var addMethod = typeof(IDictionary<string, object>).GetMethod(
"Add", new Type[] { typeof(string), typeof(object) });
// { { "PropertyName", v.PropertyName}, ... }
var elementInits = members.Select(m =>
Expression.ElementInit(addMethod, Expression.Constant(m.Member.Name), Expression.Convert(m, typeof(object))));
// new ExpandoObject()
var newExpando = Expression.New(typeof(ExpandoObject));
// new ExpandoObject() { { "PropertyName", v.PropertyName}, ... }
var expando = Expression.ListInit(newExpando, elementInits);
// (TModel v) => new ExpandoObject() { { "PropertyName", v.PropertyName}, ... }
var lambdaExpression = Expression.Lambda<Func<TModel, dynamic>>(expando, parameter);
return lambdaExpression;
}
}
This takes advantage of ExpandoObject whose members can be dynamically added and removed at run time.
The following test was used as an example of how the above function is invoked.
[TestMethod]
public void DynamicList() {
var list1 = new List<Person>
{
new Person{ Gender = "Male", Age = 10, FirstName = "Nama1", SampleNumber = 12},
new Person{ Gender = "Male", Age = 12, FirstName = "Nama2", SampleNumber = 13},
new Person{ Gender = "Female", Age = 13, FirstName = "Nama3", SampleNumber = 14},
new Person{ Gender = "Male", Age = 14, FirstName = "Nama4", SampleNumber = 15},
};
var keys = new string[] { "Age", "Gender", };
var nList = list1.AsQueryable().SelectDynamic(new HashSet<string>(keys));
foreach (IDictionary<string, object> row in nList) {
var msg = $"{{ {keys[0]} = {row[keys[0]]}, {keys[1]} = {row[keys[1]]} }}";
Debug.WriteLine(msg);
}
}
and produces the following output
{ Age = 10, Gender = Male }
{ Age = 12, Gender = Male }
{ Age = 13, Gender = Female }
{ Age = 14, Gender = Male }
The dynamic objects can be used in the View and it is a simple matter of calling the desired members.
For example suppose you have a model as follows
public class MyViewModel {
public string MyProperty { get; set; }
public string[] Keys { get; set; }
public List<dynamic> MyDynamicProperty { get; set; }
}
that was populated with data and given to the view
var list1 = _reportRepository.ShowMasteView();
var keys = new string[] { "Age", "Gender", };
var nList = list1.AsQueryable().SelectDynamic(new HashSet<string>(keys));
var viewModel = new MyViewModel {
MyProperty = "Hello World",
MyDynamicProperty = nList.ToList(),
Keys = keys
};
return View(viewModel);
Then in the view you can use the model as desired, casting to get access to members in the expando object.
#model MyViewModel
...
<h2>#Model.MyProperty</h2>
<table>
<tr>
#foreach(string key in Model.Keys) {
<th>#key</th>
}
</tr>
#foreach (IDictionary<string, object> row in Model.MyDynamicProperty) {
<tr>
#foreach(string key in Model.Keys) {
<td>#row[#key]</td>
}
</tr>
}
</table>
I think you just need to use Contains on your list2.
var nList = list1.Where(t => lits2.Contains(t1));
Contains is a method for Lists. The code you had was trying to use it on a string.
If you have two list of a person's class
public class Person
{
public int id { get; set; }
public string name { get; set; }
}
If the lists are as below:
var list1 = new List<Person>
{
new Person{ id = 1, name = "Nama1"},
new Person{ id = 2, name = "Nama2"},
new Person{ id = 3, name = "Nama3"},
new Person{ id = 4, name = "Nama4"},
};
var list2 = new List<Person>
{
new Person{ id = 1, name = "Nama1"},
new Person{ id = 2, name = "Nama2"},
};
You can filter in the following ways
var keys = list2.Select(x => x.id).ToList();
var filter1= list1.Where(x => keys.Contains(x.id)).ToList();
var filter2= list1.Where(x => keys.Contains(x.id)).Select(x => new { x.name }).ToList();
var filter3= list1.Select(x => new
{
id = x.id,
name = x.name,
check = keys.Contains(x.id)
}).Where(x => x.check).ToList();
If you have array of string
you can use below code
array string same
var lis1 = new string[] {"name1", "name2","name3" };
var lis2 = new string[] { "name1" };
You can filter array of string in the following ways
var items1= lis1.Where(x=>lis2.Contains(x)).ToList();
var items= lis1.Select(x=> new { x, check= lis2.Contains(x) }).Where(x=>x.check == true).ToList();

How to retrieve data that is in a table? PostgreSQL, AngularJS1, Spring, Hibernate

In my database I have last names and first names. I collect them in a array ; my variable lastAndFirstNameList contains: ex : [name, first name] => ( ["WOOD", "Robin"])
I then try to retrieve separately the last name and the first name with the variables lastname and firstname. I get the result « lastname undefined » and « firstname undefined ». I do not understand why! Could you help me please?
enter code here : //controller.js
Employee.getFirstAndLastName().$promise.then(function(result) {
var lastAndFirstNameList = result.list;
var lastname = lastAndFirstNameList.lastName;
var firstname = lastAndFirstNameList.firstName;
for(var k = 0; k < lastAndFirstNameList.length; k++)
{
console.log("lastname", lastname);
console.log("firstname", firstname);
}
console.log("lastAndFirstNameList", lastAndFirstNameList);
}
....
enter code here daoImpl.java
#SuppressWarnings("unchecked")
#Override
public List<Object> getFirstAndLastName() {
SQLQuery querySQL = sessionFactory.getCurrentSession().createSQLQuery("select last_name, first_name from employee");
List<Object> firstAndLastNameList = querySQL.list();
return firstAndLastNameList;
}
What does this give you? I don't think that 'firstname' and 'lastname' will give you anything because the are not referenced correctly.
Employee.getFirstAndLastName().$promise.then(function(result) {
var lastAndFirstNameList = result.list;
var lastname = lastAndFirstNameList.lastName;
var firstname = lastAndFirstNameList.firstName;
console.log("lastname ", lastname);
console.log("firstname ", firstname);
console.log("lastAndFirstNameList", lastAndFirstNameList);
}
Change the above reference variable to look like this:
var lastname = lastAndFirstNameList[0].lastName;
var firstname = lastAndFirstNameList[0].firstName;
That should give you the first value if passed correctly from the server.
Your loop should then look like this:
for(var k = 0; k < lastAndFirstNameList.length; k++){
console.log("lastname", lastAndFirstNameList[k].lastName);
console.log("firstname", firstname[k].firstName);
}

Regarding Trigger email

I have a trigger code:
Trigger AutoEmailsending on Order (after update)
{
Map<Id,Order> Orderdetail = new Map<Id,Order>();
Set<Id> Accountid = new Set<Id>();
for(order or1 : Trigger.new)
{
if(or1.Status == 'Submitted' && (or1.Subtype__c =='Offer' || or1.Subtype__c =='ASP'))
{
Orderdetail.put(or1.id,or1);
Accountid.add (or1.accountid);
}
}
List<Attachment> Attachmentlst = [Select Id,
ParentId,
Name,
BodyLength,
Body,
Description
From Attachment
where ParentId=:Orderdetail.keyset()];
Map<String, Blob> resources = new Map<String, Blob>();
for(StaticResource resource:[SELECT Name, Body FROM StaticResource where Name IN ('TC_for_France','TC_for_Italy')])
{
resources.put(resource.Name, resource.Body);
}
User currentUser = [Select Id,Phone,name from User where Id =:System.UserInfo.getUserId()];
for (attachment attachmentlst1 : attachmentlst )
{
List<String> Toaddress = new List<String>();
List<String> CCaddress = new List<String>();
String Orderid = attachmentlst1.ParentId;
String ResourceName;
String TCname;
string strHtmlBody;
String Emailaddress = UserInfo.getUserEmail();
String CustomerServiceEmail = Order_Configuration__c.getInstance().Customer_Service_Email__c;
string SellingOfficePhone = Order_Configuration__c.getInstance().Selling_Office_Phone__c;
String OrderNumber = Orderdetail.get(attachmentlst1.ParentId).OrderNumber;
List<Messaging.Emailfileattachment> fileAttachments = new List <Messaging.Emailfileattachment>();
if(Accountmap.get(Orderdetail.get(attachmentlst1.ParentId).accountid).Email_Address__c != null)
{
Toaddress.add(Accountmap.get(Orderdetail.get(attachmentlst1.ParentId).accountid).Email_Address__c);
}
String Market = Accountmap.get(Orderdetail.get(attachmentlst1.ParentId).accountid).Market__c;
CCaddress.add(emailaddress);
if(CustomerServiceEmail !=null)
CCaddress.add(CustomerServiceEmail);
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setToAddresses(Toaddress);
mail.setCcAddresses(CCaddress);
if(Orderdetail.get(attachmentlst1.ParentId).Subtype__c =='Offer' || Market=='FR')
{
mail.setSenderDisplayName('Trade Order-FR');
ResourceName = 'TC_for_France';
TCname = 'CONDITIONS_GENERALES_DEVENTE.pdf';
}
}
The trigger should send mail for the created user of the particular order,it should not send mail for last modified user of Particular order How to over come this Scenario,Dont need about the logic what i have to add lines in the trigger code

How can i get and use AspnetUsers UserId in migration configuration file?

This is the code of configuration file(seed method) of entity framework migration.
Through this code, i create a user and role for AspnetUsers table and i put the user in role named Admin.
AppUserManager userMgr = new AppUserManager(new UserStore<AppUser>(context));
AppRoleManager roleMgr = new AppRoleManager(new RoleStore<AppRole>(context));
string roleName = "Admin";
string userName = "admin#educationboard.com";
string password = "Sifre";
string email = "admin#educationboard.com";
if (!roleMgr.RoleExists(roleName))
{
roleMgr.Create(new AppRole(roleName));
}
AppUser user = userMgr.FindByName(userName);
if (user == null)
{
userMgr.Create(new AppUser { UserName = userName, Email = email },
password);
user = userMgr.FindByName(userName);
}
if (!userMgr.IsInRole(user.Id, roleName))
{
userMgr.AddToRole(user.Id, roleName);
}
foreach (AppUser dbUser in userMgr.Users)
{
dbUser.Cinsiyet = eCinsiyetler.Erkek;
}
context.SaveChanges();
Then i also create an entity named Articles, each article has an author id. I named AuthorId as UserId in Article entity. How can i get and use UserId I've just created above in following code?
var articles= new List<Article>
{
new Article{Title="Title 1", AddedDate=DateTime.Now, Content="content here.", UserId=.(What code should be here? };
articles.ForEach(p => context.Articles.AddOrUpdate(s => s.Title, p));
context.SaveChanges();
Why can't you query for the user like you did above?
AppUser user = userMgr.FindByName(userName);
if (user == null)
{
userMgr.Create(new AppUser { UserName = userName, Email = email },
password);
user = userMgr.FindByName(userName);
}
and then have user.Id?
If you have a handle in ApplicationDbContext you could easily do something like
ApplicationDbContext db = new ApplicationDbContext();
var user = db.AspNetUser.Single(x => x.UserName == username);
var id = user.Id;