Foreign key between tbls - ef-code-first

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");
/*******************************************************************************/

Related

File extension not being detected for file upload

Ok I have the following extensions I am checking in my code.
FileAttachments.FileAttachmentTypes fileAttachmentType = FileAttachments.FileAttachmentTypes.None;
The strings below in the conts are helled in a constants file
public const string wordExtensions = "docx;docm;doc";
public const string imageExtensions = "gif;tiff;tif;png;eps;raw;bmp;jpeg;jpg";
public const string excelExtensions = "csv;xml;xls;xlsb;xlsm;xlsx";
Which is then parsed down here
I am getting my extension from the File Info class as such
foreach (var fileAttachments in FormFile) {
if (fileAttachments.Length > 0) {
string filePath = Path.Combine(hostingEnvironment.WebRootPath, "Uploads");
var tennantId = GetCurrentTennantId().Result;
var settings = _context.SystemSetup.FirstOrDefault().UploadFolderPath;
string uniqueFilename = Guid.NewGuid().ToString() + "_" + fileAttachments.FileName;
string savedFileName = Path.Combine(filePath, uniqueFilename);
FileInfo infoFile = new FileInfo(savedFileName);
string extension = infoFile.Extension.Replace(".","");
Here I check the file extension Parameter above in the semi colan separated strings
if (extension.Contains(Constants.imageExtensions)) {
fileAttachmentType = FileAttachments.FileAttachmentTypes.Image;
} else if (extension.Contains("pdf")) {
fileAttachmentType = FileAttachments.FileAttachmentTypes.PDF;
} else if (extension.Contains(Constants.videoFormats)) {
fileAttachmentType = FileAttachments.FileAttachmentTypes.Video;
} else if (extension.Contains(Constants.excelExtensions)) {
fileAttachmentType = FileAttachments.FileAttachmentTypes.Excel;
} else if (extension.Contains(Constants.wordExtensions)) {
fileAttachmentType = FileAttachments.FileAttachmentTypes.Word;
} else if (extension.Contains(Constants.audioExtensions)) {
fileAttachmentType = FileAttachments.FileAttachmentTypes.Voice;
}
}
Types is just an area for categorizing them into tabs for front end display
public enum FileAttachmentTypes {
[Display(Name = "Microsoft Word")]
Word = 1,
[Display(Name = "Microsoft Excel")]
Excel = 2,
[Display(Name = "Image")]
Image = 3,
[Display(Name = "Voice Recordings")]
Voice = 4,
[Display(Name = "PDF")]
PDF = 5,
[Display(Name = "Video")]
Video = 6,
[Display(Name = "Evidence")]
Evidence = 7,
[Display(Name = "None")]
None = 8,
[Display(Name = "Notes")]
NOTES = 9,
[Display(Name = "Shared Case")]
SharedCase = 10,
[Display(Name = "Created Case")]
CreatedCase = 11
}
My Question is why is it not finding it for a word document of extension docx when its clearly there

Invalid column name in Entity Framework

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.

Migration Failed ASP.Net API

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?

How to prevent duplicate validation while updating the value without any changes?

#RequestMapping(value = "/updateYearMaster", method = RequestMethod.POST)
public String updateYearmaster(#RequestParam(value = "id", required = false) Long id,
#RequestParam(value = "fromyear", required = false) Date fromyear,
#RequestParam(value = "toyear", required = false) Date toyear,
#RequestParam(value = "status", required = false) String status,
#RequestParam(value = "yeardescription", required = false) String yeardescription, Model model) {
Yearmaster yearmaster = new Yearmaster(fromyear, toyear, status, yeardescription);
yearmaster.setId(id);
List val = yearmasterService.duplicateEditYear(fromyear, toyear, id);
if (!val.isEmpty()) {
model.addAttribute("yearmaster", yearmaster);
errorMessage = "fromyear and toyear combination is already exist";
model.addAttribute("errorMessage", errorMessage);
return "edit-year-master";
} else {
yearmasterService.save(yearmaster);
return "redirect:/yearmaster";
}
}

Save user profile information _userManager.UpdateAsync(user);

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)
},

Resources