I have an ASP.MET application. I performed the tutorial on code first migrations. When I executed the commands, the following code was generated for the user table:
CreateTable(
"dbo.AspNetUsers",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
ApplicationId = c.Guid(nullable: false),
Email = c.String(maxLength: 256),
EmailConfirmed = c.Boolean(nullable: false),
PasswordHash = c.String(),
SecurityStamp = c.String(),
PhoneNumber = c.String(),
PhoneNumberConfirmed = c.Boolean(nullable: false),
TwoFactorEnabled = c.Boolean(nullable: false),
LockoutEndDateUtc = c.DateTime(),
LockoutEnabled = c.Boolean(nullable: false),
AccessFailedCount = c.Int(nullable: true),
UserName = c.String(nullable: false, maxLength: 256),
Discriminator = c.String(),
LegacyPasswordHash = c.String(),
})
.PrimaryKey(t => t.Id)
.Index(t => t.UserName, unique: true, name: "UserNameIndex");
My problem is that I don't need some columns. So, I removed the code from those columns and updated my DB. But, when I try to authenticate a user, I get this error:
Invalid column name 'EmailConfirmed'.
Invalid column name 'PhoneNumberConfirmed'.
Invalid column name 'TwoFactorEnabled'.
Invalid column name 'LockoutEndDateUtc'.
Invalid column name 'LockoutEnabled'.
Invalid column name 'AccessFailedCount'.
But these columns no longer exist because I deleted them.
Or, is it possible to put it back and assign them default values for example:
EmailConfirmed = false
PhoneNumberConfirmed = false
to avoid making an insertion when creating a user. I use EF 6.2.0
Need help please.
Related
I have written a test for edit model of a class in EF core.
public async Task<Expense> EditExpense(Expense model)
{
var expense = _dataRepository.Where<Expense>(x => x.Id == model.Id).ToList();
if(expense != null)
{
expense.ForEach(x =>
{
x.Name = model.Name;
x.AddedOn = model.AddedOn;
x.Amount = model.Amount;
x.Type = model.Type;
x.SplitOption = model.SplitOption;
x.Notes = model.Notes;
x.IsGroupExpense = model.IsGroupExpense;
});
return expense.FirstOrDefault();
}
else
{
return null;
}
}
I want to test this method using xUnit and Moq and I have also written a method for it as below.
[Fact]
public async void UnitTest_IsExpenseEdited_ReturnsTrue()
{
var expenseCurrent = new Expense()
{
Id = 5,
Name = "Test Expense",
Amount = 1500,
AddedBy = "44db32c3-ad6a-4d68-a683-862be363f59c",
AddedOn = DateTime.Now,
Notes = "",
IsDeleted = false,
IsGroupExpense = false,
SplitOption = 1,
Type = 0
};
var expenseList = (new List<Expense>{ expenseCurrent });
var expenseAfterEdit = new Expense()
{
Id = 5,
Name = "Test Expense Edited",
Amount = 2000,
AddedBy = "44db32c3-ad6a-4d68-a683-862be363f59c",
AddedOn = DateTime.Now,
Notes = "Edited !!!",
IsDeleted = false,
IsGroupExpense = true,
SplitOption = 2,
Type = 0
};
_dataRepositoryMock.Setup(x => x.Where<Expense>(a => a.Id == expenseCurrent.Id)).Returns(expenseList as IQueryable<Expense>);
var expenseEdited = await _exepenseRepository.EditExpense(expenseAfterEdit);
Assert.Equal(expenseEdited, expenseAfterEdit);
}
But here, the Where method is returning null
public async Task<Expense> EditExpense(Expense model)
{
var expense = _dataRepository.Where<Expense>(x => x.Id == model.Id).ToList(); in repository
}
I am getting var expense null in above code.
Please suggest what should I include in the code to get the value in above var expense?
To test this method, I want to create a fake data which is going to be updated. Please suggest how this thing needs to be written properly?
I have problem when I'm trying to update the database.
I'm making web-api with asp.net.
I just added new migration and works perfectly. Then updated my database with update-database command. Then I change some codes. When I add new migration it said:
Unable to generate an explicit migration because the following explicit migrations are pending:
[201705310248355_changeProduct, 201706191007322_ModifyModel, 201707170631209_changeProductModel, 201707170652556_EditProductModelLagi, 201707180312064_AddStorageIdOnInventory, 201707190243206_ChangeRepository, 201708091124374_EditInventory, 201803130702299_testBoom].
Apply the pending explicit migrations before attempting to generate a new explicit migration.
but last time I updated the database it works perfectly
PM> update-database -target testboom -startupprojectname ShopDiaryProject.EF -force
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Target database is already at version 201803130702299_testBoom.
Soo, I tried to add-migration with -force parameter.
It works!
BUT,
I update the database again, the migration content likes start from beginning and can't add tables.
Here are my migration:
public override void Up()
{
CreateTable(
"dbo.Categories",
c => new
{
Id = c.Guid(nullable: false),
Name = c.String(maxLength: 200),
Description = c.String(maxLength: 200),
UserId = c.Guid(nullable: false),
CreatedDate = c.DateTime(nullable: false),
ModifiedDate = c.DateTime(),
DeletedDate = c.DateTime(),
CreatedUserId = c.String(),
ModifiedUserId = c.String(),
DeletedUserID = c.String(),
IsDeleted = c.Boolean(nullable: false),
User_Id = c.String(maxLength: 128),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AspNetUsers", t => t.User_Id)
.Index(t => t.User_Id);
CreateTable(
"dbo.Products",
c => new
{
Id = c.Guid(nullable: false),
Name = c.String(maxLength: 250),
BarcodeId = c.String(maxLength: 250),
CategoryId = c.Guid(nullable: false),
CreatedDate = c.DateTime(nullable: false),
ModifiedDate = c.DateTime(),
DeletedDate = c.DateTime(),
CreatedUserId = c.String(),
ModifiedUserId = c.String(),
DeletedUserID = c.String(),
IsDeleted = c.Boolean(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Categories", t => t.CategoryId, cascadeDelete: true)
.Index(t => t.CategoryId);
CreateTable(
"dbo.Shopitems",
c => new
{
Id = c.Guid(nullable: false),
Quantity = c.Int(nullable: false),
price = c.Decimal(nullable: false, precision: 18, scale: 2),
ProductId = c.Guid(nullable: false),
ShoplistId = c.Guid(nullable: false),
CreatedDate = c.DateTime(nullable: false),
ModifiedDate = c.DateTime(),
DeletedDate = c.DateTime(),
CreatedUserId = c.String(),
ModifiedUserId = c.String(),
DeletedUserID = c.String(),
IsDeleted = c.Boolean(nullable: false),
})
and it said There is already an object named 'Categories' in the database.
Any ideas?
i create Table with Code First and create table with fluentapi .
how can i create Foreign key between them ?
public partial class Tbl_Gender
{
[Key]
public int GendID { get; set; }
[Required]
[StringLength(150)]
public GenType GendType { get; set; }
}
public enum GenType
{
Male = 1,
Fmale = 2
}
}
.
CreateTable(
"dbo.AspNetUsers",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
Name = c.String(),
Family = c.String(),
UserPhoto = c.String(),
RoleID = c.String(),
Gender = c.String(),
Email = c.String(maxLength: 256),
EmailConfirmed = c.Boolean(nullable: false),
PasswordHash = c.String(),
SecurityStamp = c.String(),
PhoneNumber = c.String(),
PhoneNumberConfirmed = c.Boolean(nullable: false),
TwoFactorEnabled = c.Boolean(nullable: false),
LockoutEndDateUtc = c.DateTime(),
LockoutEnabled = c.Boolean(nullable: false),
AccessFailedCount = c.Int(nullable: false),
UserName = c.String(nullable: false, maxLength: 256),
})
.PrimaryKey(t => t.Id)
.Index(t => t.UserName, unique: true, name: "UserNameIndex");
/*******************************************************************************/
I'm trying to get Microsoft.AspNet.Identity.EntityFramework": "3.0.0-beta6 to write some information to the current ApplicationUser "profile" but the value is null and I don't get any exceptions running the following code.
public class TestController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
public TestController(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
// GET: /<controller>/
public async Task<ActionResult> Index()
{
var userObject = await _userManager.FindByIdAsync(Context.User.GetUserId());
//This value is null even the second time I hit this breakpoint.
var shouldHaveAValue = userObject.MyStringList;
userObject.MyStringList = new List<string>();
userObject.MyStringList.Add("testId");
await _userManager.UpdateAsync(userObject);
return View();
}
}
I might be completely wrong here but this is the way I figured it should be done when I saw
// Add profile data for application users by adding properties to the ApplicationUser class
public class ApplicationUser : IdentityUser
{
public virtual List<string> MyStringList { get; set; }
}
The example is implemented in the ASP.NET5 web template.
//Edit:
Could it be the way I added the column? I did this since I get errors running the migrations commands which is stated not to be ready on the ef documentation page.( dnx . ef apply )
migration.CreateTable(
name: "AspNetUsers",
columns: table => new
{
Id = table.Column(type: "nvarchar(450)", nullable: false),
AccessFailedCount = table.Column(type: "int", nullable: false),
ConcurrencyStamp = table.Column(type: "nvarchar(max)", nullable: true),
Email = table.Column(type: "nvarchar(max)", nullable: true),
EmailConfirmed = table.Column(type: "bit", nullable: false),
LockoutEnabled = table.Column(type: "bit", nullable: false),
LockoutEnd = table.Column(type: "datetimeoffset", nullable: true),
NormalizedEmail = table.Column(type: "nvarchar(max)", nullable: true),
NormalizedUserName = table.Column(type: "nvarchar(max)", nullable: true),
PasswordHash = table.Column(type: "nvarchar(max)", nullable: true),
PhoneNumber = table.Column(type: "nvarchar(max)", nullable: true),
PhoneNumberConfirmed = table.Column(type: "bit", nullable: false),
SecurityStamp = table.Column(type: "nvarchar(max)", nullable: true),
TwoFactorEnabled = table.Column(type: "bit", nullable: false),
UserName = table.Column(type: "nvarchar(max)", nullable: true),
MyStringList = table.Column(type: "nvarchar(max)", nullable: true)
},
So my problem is that I've got to mock two things. One is a method that finds a person and the other is a list of those people over which it iterates. However it doesn't get both setups but only 1. I've tried putting them in different orders and each time only the top 1 works.
here's my code:
Person test = new Person()
{
City = "Eindhoven Area, Netherlands.",
userid = 1,
ID = 1,
Email = "fraylight#gmail.com",
ExtraInfo = "blabla",
HobbyProjectICTRelated = "a",
Hobbys = "",
LearntSkillsAndLevelOfSkills = "Java:7, C#:4, Software Documentation:4, Software Development:4, HTML:2, CSS:2, jQuery:1",
Name = "Marijn van Donkelaar",
PhoneNr = "0612345678",
ProfileImage = "/Images/hollemar.jpg",
SkillsToLearn = "ASP.net:2, JAVA:3",
Stand = "",
Summary = "",
YearsOfWorkExperience = 6,
PeopleManagerApproved = true,
PeopleManager = "Richard"
};
Person test1 = new Person()
{
City = "Eindhoven Area, Netherlands.",
userid = 2,
ID = 2,
Email = "fraylight#gmail.com",
ExtraInfo = "",
HobbyProjectICTRelated = "a",
Hobbys = "zwemmen",
LearntSkillsAndLevelOfSkills = "Java:8, C#:4, Software Documentation:4, Software Development:4, HTML:2, CSS:2, jQuery:1",
Name = "Richard Holleman",
PhoneNr = "",
ProfileImage = "/Images/hollemar.jpg",
SkillsToLearn = "ASP.net:2, JAVA:2",
Stand = "",
Summary = "",
YearsOfWorkExperience = 16,
PeopleManagerApproved = true,
PeopleManager = "Richard"
};
Person test2 = new Person()
{
City = "Eindhoven Area, Netherlands.",
userid = 3,
ID = 3,
Email = "fraylight#gmail.com",
ExtraInfo = "",
HobbyProjectICTRelated = "",
Hobbys = "zwemmen",
LearntSkillsAndLevelOfSkills = "C#:4, SQL:4, PLSQL:4, HTML:2, CSS:2, jQuery:1",
Name = "Jasmine Test",
PhoneNr = "0612345678",
ProfileImage = "/Images/hollemar.jpg",
SkillsToLearn = "ASP.net:2, JAVA:1",
Stand = "",
Summary = "",
YearsOfWorkExperience = 11,
PeopleManagerApproved = true,
PeopleManager = "Richard"
};
var data = new List<Person> { test, test1, test2 }.AsQueryable();
var dbSetMock = new Mock<IDbSet<Person>>();
dbSetMock.Setup(m => m.Provider).Returns(data.Provider);
dbSetMock.Setup(m => m.Expression).Returns(data.Expression);
dbSetMock.Setup(m => m.ElementType).Returns(data.ElementType);
dbSetMock.Setup(m => m.GetEnumerator()).Returns(() => data.GetEnumerator());
var mockContext = new Mock<PersonDBContext>();
mockContext.Setup(x => x.Persons).Returns(dbSetMock.Object);
mockContext.Setup(x => x.Persons.Find(1)).Returns(test);
var service = new PersonController(mockContext.Object);
var controllerContext = new Mock<ControllerContext>();
controllerContext.Setup(t => t.HttpContext.Session["loggedinuser"]).Returns(10);
service.ControllerContext = controllerContext.Object;
ViewResult detailspageresultcorrect = (ViewResult) service.Details(10);
Person resultpersoncorrect = (Person) detailspageresultcorrect.Model;
Assert.IsTrue(resultpersoncorrect.Name.Equals(test.Name));
The part where it goes wrong is on the line of: var mockContext = new Mock();
You should be able to mock the Find method directed on the IDbSet instead of going via the Persons property.
So your setups would look like the following:
var dbSetMock = new Mock<IDbSet<Person>>();
dbSetMock.Setup(m => m.Provider).Returns(data.Provider);
dbSetMock.Setup(m => m.Expression).Returns(data.Expression);
dbSetMock.Setup(m => m.ElementType).Returns(data.ElementType);
dbSetMock.Setup(m => m.GetEnumerator()).Returns(() => data.GetEnumerator());
dbSetMock.Setup(m => m.Find(1)).Returns(test);
var mockContext = new Mock<PersonDBContext>();
mockContext.Setup(x => x.Persons).Returns(dbSetMock.Object);