EF6 Seed Data Incorrect on first pass - ef-code-first
I am using EF6 code first to push my model to a database. Everything is working great in terms of creating the database and it does execute the seed commands as expected. The problem is that some of the seeds that are placed in my database on the first run of update-database command are incorrect. A subsequent run of update-database will correctly update the seeds to their expected values.
I have done the following:
Removed the migrations folder and reset the migrations.
Deleted my code base, and pulled a fresh copy from source control.
Tried the update-database command from different machines with the same results.
Any Suggestions?
Updates:
Here is my model:
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using CustomerPortal.Website.Models.Enums;
namespace CustomerPortal.Website.Models
{
[Table("Document")]
public class Document
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int DocumentUID { get; set; }
[ForeignKey("DocumentType")]
[Required]
public int DocumentTypeUID { get; set; }
public virtual DocumentType DocumentType { get; set; }
[Required]
[StringLength(36)]
public string DocumentToken { get; set; }
[Required]
[StringLength(255)]
public string DocumentName { get; set; }
[StringLength(50)]
public string FormNumber { get; set; }
[Required]
public bool IsActive { get; set; }
[Required]
public bool SendToParticipant { get; set; }
[Required]
public bool RequiresTransformation { get; set; }
[NotMapped]
public DocumentTypeCode DocumentTypeCode
{
get { return (DocumentTypeCode)DocumentTypeUID; }
set { DocumentTypeUID = (int)value; }
}
}
}
Here is my DBMigrationsConfiguration
using System.Collections.Generic;
using System.Data.Entity.Migrations.Model;
using System.Data.Entity.SqlServer;
using System.Data.Entity.Migrations;
using CustomerPortal.Website.DAL;
namespace CustomerPortal.Website.Migrations
{
internal sealed class Configuration : DbMigrationsConfiguration<ApplicationDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true;
SetSqlGenerator("System.Data.SqlClient", new CustomSqlServerMigrationSqlGenerator());
}
internal class CustomSqlServerMigrationSqlGenerator : SqlServerMigrationSqlGenerator
{
protected override void Generate(AddColumnOperation addColumnOperation)
{
SetCreatedUtcColumn(addColumnOperation.Column);
base.Generate(addColumnOperation);
}
protected override void Generate(CreateTableOperation createTableOperation)
{
SetCreatedUtcColumn(createTableOperation.Columns);
base.Generate(createTableOperation);
}
private static void SetCreatedUtcColumn(IEnumerable<ColumnModel> columns)
{
foreach (var columnModel in columns)
{
SetCreatedUtcColumn(columnModel);
}
}
private static void SetCreatedUtcColumn(PropertyModel column)
{
if (column.Name == "CreatedOnDate" || column.Name == "UpdatedOnDate")
{
column.DefaultValueSql = "GETUTCDATE()";
}
}
}
protected override void Seed(ApplicationDbContext context)
{
SeedProcess.SeedDatabase(context);
}
}
}
Here is my SeedProcess Class:
using CustomerPortal.Website.DAL.Seeds;
namespace CustomerPortal.Website.DAL
{
public class SeedProcess
{
public static void SeedDatabase(ApplicationDbContext context)
{
DocumentTypeSeeds.Seed(context);
SiteImageTypeSeeds.Seed(context);
SubscriptionTypeSeeds.Seed(context);
DocumentEntityTypeSeeds.Seed(context);
StateTypeSeeds.Seed(context);
PaymentTransactionTypeSeeds.Seed(context);
PayerTypeSeeds.Seed(context);
BenefitPayoutTypeSeeds.Seed(context);
BillingFrequencyTypeSeeds.Seed(context);
CriteriaExpressionTypeSeeds.Seed(context);
FamilyCoverageTypeSeeds.Seed(context);
InstitutionTypeSeeds.Seed(context);
PaymentTypeSeeds.Seed(context);
ProductEnrollmentTypeSeeds.Seed(context);
ProductTypeSeeds.Seed(context);
ProductRateTypeSeeds.Seed(context);
BenefitTypeSeeds.Seed(context);
PotentialEnrolleeStatusTypeSeeds.Seed(context);
//Image and Document Seeds
SiteImageSeeds.Seed(context);
DocumentSeeds.Seed(context);
//Base Product & Setup Seeds
InstitutionSeeds.Seed(context);
ProductSeeds.Seed(context);
BenefitSeeds.Seed(context);
ProductBenefitSeeds.Seed(context);
OfferSeeds.Seed(context);
PlanSeeds.Seed(context);
PlanProductBenefitSeeds.Seed(context);
PlanCoverageSeeds.Seed(context);
PlanCoverageRateSeeds.Seed(context);
CriteriaGroupSeeds.Seed(context);
CriteriaSeeds.Seed(context);
CriteriaGroupCriteriaSeeds.Seed(context);
RoleSeeds.Seed(context);
UserSeeds.Seed(context);
//Customer Specific Offer Seeds
FormGroupSeeds.Seed(context);
FormGroupFormSeeds.Seed(context);
InstitutionOfferGroupSeeds.Seed(context);
InstitutionOfferGroupOfferSeeds.Seed(context);
InstitutionOfferGroupPaymentOptionSeeds.Seed(context);
//Seed Document Relations
InstitutionDocumentSeeds.Seed(context);
InstitutionOfferGroupDocumentSeeds.Seed(context);
PlanCoverageDocumentSeeds.Seed(context);
ProductDocumentSeeds.Seed(context);
ProductStateDocumentSeeds.Seed(context);
ProductMarketableStateSeeds.Seed(context);
}
}
}
And Finally here is the DocumentSeed class that doesnt seed correctly:
using CustomerPortal.Website.DAL;
using CustomerPortal.Website.Models;
using System.Data.Entity.Migrations;
namespace CustomerPortal.Website.DAL.Seeds
{
public static class DocumentSeeds
{
public static void Seed(ApplicationDbContext context)
{
context.Documents.AddOrUpdate(
new Document
{
DocumentUID = 1,
DocumentTypeUID = 2,
DocumentToken = "834cc814-1321-4ef3-8bcd-5de0c66b71e7",
DocumentName = "Crescent Medical Setup Doc.docx",
FormNumber = "N/A",
IsActive = true,
SendToParticipant = false,
RequiresTransformation = false
},
//This is the problem seed.
//DocumentUID 2 should be the welcome letter
//But on intial seed, its a privacy policy, which is actually Document UID 39
new Document
{
DocumentUID = 2,
DocumentTypeUID = 3,
DocumentToken = "af9b59e3-0270-45f4-ae7c-eb03602fc049",
DocumentName = "Crescent Medical Welcome Letter",
FormNumber = "N/A",
IsActive = true,
SendToParticipant = true,
RequiresTransformation = false
}
,
new Document
{
DocumentUID = 3,
DocumentTypeUID = 4,
DocumentToken = "2f7f6ba0-c9ee-47f0-af6c-7672a536e7e1",
DocumentName = "AD&D AME Voluntary DOC Plan 1 Family 99078299.doc",
FormNumber = "DOC-99078299-1F",
IsActive = true,
SendToParticipant = true,
RequiresTransformation = false
}
,
new Document
{
DocumentUID = 4,
DocumentTypeUID = 4,
DocumentToken = "d00b8f58-2229-4206-a759-06eb764f493f",
DocumentName = "AD&D AME Voluntary DOC Plan 1 Single + 1 99078299.doc",
FormNumber = "DOC-99078299-1 S1",
IsActive = true,
SendToParticipant = true,
RequiresTransformation = false
}
,
new Document
{
DocumentUID = 5,
DocumentTypeUID = 4,
DocumentToken = "17e346c9-0abd-4d14-bb21-124fe15649e7",
DocumentName = "AD&D AME Voluntary DOC Plan 1 Single 99078299.doc",
FormNumber = "DOC-99078299-1S",
IsActive = true,
SendToParticipant = true,
RequiresTransformation = false
}
,
new Document
{
DocumentUID = 6,
DocumentTypeUID = 4,
DocumentToken = "29c0391a-f657-49b1-9692-842d97dc1517",
DocumentName = "AD&D AME Voluntary DOC Plan 2 Family 99078299.doc",
FormNumber = "DOC-99078299-2F",
IsActive = true,
SendToParticipant = true,
RequiresTransformation = false
}
,
new Document
{
DocumentUID = 7,
DocumentTypeUID = 4,
DocumentToken = "1cfd5698-9b23-48e5-9096-30d007a395f6",
DocumentName = "AD&D AME Voluntary DOC Plan 2 Single + 1 99078299.doc",
FormNumber = "DOC-99078299-2 S1",
IsActive = true,
SendToParticipant = true,
RequiresTransformation = false
}
,
new Document
{
DocumentUID = 8,
DocumentTypeUID = 4,
DocumentToken = "b46f2716-aed9-4096-950f-6a7374bc7961",
DocumentName = "AD&D AME Voluntary DOC Plan 2 Single 99078299.doc",
FormNumber = "DOC-99078299-2S",
IsActive = true,
SendToParticipant = true,
RequiresTransformation = false
}
,
new Document
{
DocumentUID = 9,
DocumentTypeUID = 4,
DocumentToken = "815d0259-636a-4d1f-9d8e-6a55e2fb3463",
DocumentName = "AD&D AME Voluntary DOC Plan 3 Family 99078299.doc",
FormNumber = "DOC-99078299-3F",
IsActive = true,
SendToParticipant = true,
RequiresTransformation = false
}
,
new Document
{
DocumentUID = 10,
DocumentTypeUID = 4,
DocumentToken = "80a0c5c9-83fb-4f38-a3f2-349d174b58e6",
DocumentName = "AD&D AME Voluntary DOC Plan 3 Single + 1 99078299.doc",
FormNumber = "DOC-99078299-3 S1",
IsActive = true,
SendToParticipant = true,
RequiresTransformation = false
}
,
new Document
{
DocumentUID = 11,
DocumentTypeUID = 4,
DocumentToken = "427a74d6-9df8-4e3a-b84b-29c006af2203",
DocumentName = "AD&D AME Voluntary DOC Plan 3 Single 99078299.doc",
FormNumber = "DOC-99078299-3S",
IsActive = true,
SendToParticipant = true,
RequiresTransformation = false
}
,
new Document
{
DocumentUID = 12,
DocumentTypeUID = 4,
DocumentToken = "6323d281-8f1b-4bd0-9ac3-7c624fb8046a",
DocumentName = "AD&D AME Voluntary DOC Plan 4 Family 99078299.doc",
FormNumber = "DOC-99078299-4F",
IsActive = true,
SendToParticipant = true,
RequiresTransformation = false
}
,
new Document
{
DocumentUID = 13,
DocumentTypeUID = 4,
DocumentToken = "eb51b5e5-2cb1-4c99-96f1-c709120c3cb4",
DocumentName = "AD&D AME Voluntary DOC Plan 4 Single + 1 99078299.doc",
FormNumber = "DOC-99078299-4 S1",
IsActive = true,
SendToParticipant = true,
RequiresTransformation = false
}
,
new Document
{
DocumentUID = 14,
DocumentTypeUID = 4,
DocumentToken = "0a390297-e77e-44b9-bb8a-ae39f25129f0",
DocumentName = "AD&D AME Voluntary DOC Plan 4 Single 99078299.doc",
FormNumber = "DOC-99078299-4S",
IsActive = true,
SendToParticipant = true,
RequiresTransformation = false
}
,
new Document
{
DocumentUID = 15,
DocumentTypeUID = 4,
DocumentToken = "3ec07cc2-7228-49b3-b25f-b77450c61cd7",
DocumentName = "ASHIP DOC Plan 1 Family 99078298.doc",
FormNumber = "ASHIP5000-DOC RI",
IsActive = true,
SendToParticipant = true,
RequiresTransformation = false
}
,
new Document
{
DocumentUID = 16,
DocumentTypeUID = 4,
DocumentToken = "dfb57cd5-ba6a-43d0-b66e-bd22b5cca595",
DocumentName = "ASHIP DOC Plan 1 Single + Child 99078298.doc",
FormNumber = "ASHIP5000-DOC RI",
IsActive = true,
SendToParticipant = true,
RequiresTransformation = false
}
,
new Document
{
DocumentUID = 17,
DocumentTypeUID = 4,
DocumentToken = "be9260b6-8191-4a25-bda3-0d5a39049714",
DocumentName = "ASHIP DOC Plan 1 Single + Spouse 99078298.doc",
FormNumber = "ASHIP5000-DOC RI",
IsActive = true,
SendToParticipant = true,
RequiresTransformation = false
}
,
new Document
{
DocumentUID = 18,
DocumentTypeUID = 4,
DocumentToken = "c5d68d60-a0c0-4dd4-9d7b-8beeaa92b195",
DocumentName = "ASHIP DOC Plan 1 Single 99078298.doc",
FormNumber = "ASHIP5000-DOC RI",
IsActive = true,
SendToParticipant = true,
RequiresTransformation = false
}
,
new Document
{
DocumentUID = 19,
DocumentTypeUID = 4,
DocumentToken = "b83d2f96-863a-4ab4-a665-f239b2dcf927",
DocumentName = "ASHIP DOC Plan 2 Family 99078298.doc",
FormNumber = "ASHIP5000-DOC RI",
IsActive = true,
SendToParticipant = true,
RequiresTransformation = false
}
,
new Document
{
DocumentUID = 20,
DocumentTypeUID = 4,
DocumentToken = "0608d614-fa94-40bb-9d02-13d77aa9d116",
DocumentName = "ASHIP DOC Plan 2 Single + Child 99078298.doc",
FormNumber = "ASHIP5000-DOC RI",
IsActive = true,
SendToParticipant = true,
RequiresTransformation = false
}
,
new Document
{
DocumentUID = 21,
DocumentTypeUID = 4,
DocumentToken = "84022349-3f83-414e-8636-dfcad5b68b2e",
DocumentName = "ASHIP DOC Plan 2 Single + Spouse 99078298.doc",
FormNumber = "ASHIP5000-DOC RI",
IsActive = true,
SendToParticipant = true,
RequiresTransformation = false
}
,
new Document
{
DocumentUID = 22,
DocumentTypeUID = 4,
DocumentToken = "85169edb-b2b7-4633-9036-4090daabd924",
DocumentName = "ASHIP DOC Plan 2 Single 99078298.doc",
FormNumber = "ASHIP5000-DOC RI",
IsActive = true,
SendToParticipant = true,
RequiresTransformation = false
}
,
new Document
{
DocumentUID = 23,
DocumentTypeUID = 4,
DocumentToken = "c4b9cfd6-23db-4727-a05c-d8e3b897b28e",
DocumentName = "ASHIP DOC Plan 3 Family 99078298.doc",
FormNumber = "ASHIP5000-DOC RI",
IsActive = true,
SendToParticipant = true,
RequiresTransformation = false
}
,
new Document
{
DocumentUID = 24,
DocumentTypeUID = 4,
DocumentToken = "02de6cb2-0db4-4b90-8a6c-c87a1d5648ef",
DocumentName = "ASHIP DOC Plan 3 Single + Child 99078298.doc",
FormNumber = "ASHIP5000-DOC RI",
IsActive = true,
SendToParticipant = true,
RequiresTransformation = false
}
,
new Document
{
DocumentUID = 25,
DocumentTypeUID = 4,
DocumentToken = "87710917-e9b2-45e9-be24-dfa1ebbebc9c",
DocumentName = "ASHIP DOC Plan 3 Single + Spouse 99078298.doc",
FormNumber = "ASHIP5000-DOC RI",
IsActive = true,
SendToParticipant = true,
RequiresTransformation = false
}
,
new Document
{
DocumentUID = 26,
DocumentTypeUID = 4,
DocumentToken = "aac423ea-8c22-401c-96b2-9b241f34c87c",
DocumentName = "ASHIP DOC Plan 3 Single 99078298.doc",
FormNumber = "ASHIP5000-DOC RI",
IsActive = true,
SendToParticipant = true,
RequiresTransformation = false
}
,
new Document
{
DocumentUID = 27,
DocumentTypeUID = 4,
DocumentToken = "beb27c9f-2c1f-4b30-a1bc-f5e0c76941a1",
DocumentName = "ASHIP DOC Plan 4 Family 99078298.doc",
FormNumber = "ASHIP5000-DOC RI",
IsActive = true,
SendToParticipant = true,
RequiresTransformation = false
}
,
new Document
{
DocumentUID = 28,
DocumentTypeUID = 4,
DocumentToken = "1fff7ab9-34a3-420b-96af-1872a14c464b",
DocumentName = "ASHIP DOC Plan 4 Single + Child 99078298.doc",
FormNumber = "ASHIP5000-DOC RI",
IsActive = true,
SendToParticipant = true,
RequiresTransformation = false
}
,
new Document
{
DocumentUID = 29,
DocumentTypeUID = 4,
DocumentToken = "c9f87921-72a1-4cd5-91a5-91942da063fd",
DocumentName = "ASHIP DOC Plan 4 Single + Spouse 99078298.doc",
FormNumber = "ASHIP5000-DOC RI",
IsActive = true,
SendToParticipant = true,
RequiresTransformation = false
}
,
new Document
{
DocumentUID = 30,
DocumentTypeUID = 4,
DocumentToken = "0ed44913-35b6-4233-9367-bd023fcac0a2",
DocumentName = "ASHIP DOC Plan 4 Single 99078298.doc",
FormNumber = "ASHIP5000-DOC RI",
IsActive = true,
SendToParticipant = true,
RequiresTransformation = false
}
,
new Document
{
DocumentUID = 31,
DocumentTypeUID = 4,
DocumentToken = "e75b63fd-1a7e-40e7-9c0e-482684668f12",
DocumentName = "CI DOC Plan 1 Primary + Sp 99078320.docx",
FormNumber = "Form 44-10-0672 (Ed. 03-14) RI",
IsActive = true,
SendToParticipant = true,
RequiresTransformation = false
}
,
new Document
{
DocumentUID = 32,
DocumentTypeUID = 4,
DocumentToken = "407a0587-3b06-4a7a-a55f-b354b5f41e3b",
DocumentName = "CI DOC Plan 1 Primary 99078320.docx",
FormNumber = "Form 44-10-0672 (Ed. 03-14) RI",
IsActive = true,
SendToParticipant = true,
RequiresTransformation = false
}
,
new Document
{
DocumentUID = 33,
DocumentTypeUID = 4,
DocumentToken = "59928258-c18b-4421-ac64-a37b484405e5",
DocumentName = "CI DOC Plan 2 Primary + Sp 99078320.docx",
FormNumber = "Form 44-10-0672 (Ed. 03-14) RI",
IsActive = true,
SendToParticipant = true,
RequiresTransformation = false
}
,
new Document
{
DocumentUID = 34,
DocumentTypeUID = 4,
DocumentToken = "9782f1a3-2f44-4d01-b2f8-25e894afaf5a",
DocumentName = "CI DOC Plan 2 Primary 99078320.docx",
FormNumber = "Form 44-10-0672 (Ed. 03-14) RI",
IsActive = true,
SendToParticipant = true,
RequiresTransformation = false
}
,
new Document
{
DocumentUID = 35,
DocumentTypeUID = 4,
DocumentToken = "20ccd21b-2ee4-421e-bbe3-c38d60802400",
DocumentName = "CI DOC Plan 3 Primary + Sp 99078320.docx",
FormNumber = "Form 44-10-0672 (Ed. 03-14) RI",
IsActive = true,
SendToParticipant = true,
RequiresTransformation = false
}
,
new Document
{
DocumentUID = 36,
DocumentTypeUID = 4,
DocumentToken = "e72db228-fc77-4d19-b681-e3e0a0ad3a95",
DocumentName = "CI DOC Plan 3 Primary 99078320.docx",
FormNumber = "Form 44-10-0672 (Ed. 03-14) RI",
IsActive = true,
SendToParticipant = true,
RequiresTransformation = false
}
,
new Document
{
DocumentUID = 37,
DocumentTypeUID = 4,
DocumentToken = "0d69aedf-53e2-4105-a6bb-3a976d8bf366",
DocumentName = "CI DOC Plan 4 Primary + Sp 99078320.docx",
FormNumber = "Form 44-10-0672 (Ed. 03-14) RI",
IsActive = true,
SendToParticipant = true,
RequiresTransformation = false
}
,
new Document
{
DocumentUID = 38,
DocumentTypeUID = 4,
DocumentToken = "f5e3a49c-2eb6-425d-91ee-ed8e5ed29b89",
DocumentName = "CI DOC Plan 4 Primary 99078320.docx",
FormNumber = "Form 44-10-0672 (Ed. 03-14) RI",
IsActive = true,
SendToParticipant = true,
RequiresTransformation = false
}
,
new Document
{
DocumentUID = 39,
DocumentTypeUID = 1,
DocumentToken = "33274185-c673-44ed-b8e5-2a10b6d34263",
DocumentName = "Crescent Medical Bridge Privacy Policy.docx",
FormNumber = null,
IsActive = true,
SendToParticipant = true,
RequiresTransformation = false
}
,
new Document
{
DocumentUID = 40,
DocumentTypeUID = 7,
DocumentToken = "ab2395f5-dbe5-405c-9bc4-c0e90166e55f",
DocumentName = "AD&D AME Basic Policy 99078426.pdf",
FormNumber = null,
IsActive = true,
SendToParticipant = false,
RequiresTransformation = false
}
,
new Document
{
DocumentUID = 41,
DocumentTypeUID = 7,
DocumentToken = "e2a59a6e-50e9-4dcd-9e40-8ced64a30568",
DocumentName = "AD&D AME Voluntary Policy 99078299.pdf",
FormNumber = null,
IsActive = true,
SendToParticipant = false,
RequiresTransformation = false
}
,
new Document
{
DocumentUID = 42,
DocumentTypeUID = 7,
DocumentToken = "35f7384f-d268-4762-af20-1194e9b95213",
DocumentName = "ASHIP Policy Blanket 99078349.pdf",
FormNumber = null,
IsActive = true,
SendToParticipant = false,
RequiresTransformation = false
}
,
new Document
{
DocumentUID = 43,
DocumentTypeUID = 7,
DocumentToken = "5c60fcfd-1b78-47e4-b5af-f2e4f15ed95d",
DocumentName = "ASHIP Voluntary Policy 99078298.pdf",
FormNumber = null,
IsActive = true,
SendToParticipant = false,
RequiresTransformation = false
}
,
new Document
{
DocumentUID = 44,
DocumentTypeUID = 7,
DocumentToken = "caca3175-06f0-4e40-8c7a-e0e1ba937051",
DocumentName = "CI Policy 99078337 embedded.pdf",
FormNumber = null,
IsActive = true,
SendToParticipant = false,
RequiresTransformation = false
}
,
new Document
{
DocumentUID = 45,
DocumentTypeUID = 7,
DocumentToken = "e66f05b0-61e3-4662-885d-576993a9ed6f",
DocumentName = "CI Vol Policy 99078320.pdf",
FormNumber = null,
IsActive = true,
SendToParticipant = false,
RequiresTransformation = false
}
);
}
}
}
Initial Seed Records in Database:
InitialSeedData
Seed Data after subsequent updata-database command:
SubsequentSeedData
Update:
I added the following code to the top of the SeedDatabase Method:
if (System.Diagnostics.Debugger.IsAttached == false)
System.Diagnostics.Debugger.Launch();
This allowed me to debug the seed method being called during the update-database command.
The underlying issue appears to be the fact that at some point, a snap shot was taken of the data inside my model and is being stored somewhere in the code. This snap shot of data is already in the context before the seed method is called initially.
I am using AddOrUpdate extension and for some reason even though the object is different from the snapshot data, the seed model data is not changed on the first call.
Regardless, the work around is to simply to clear the Documents table at the top of the seed method. This obviously just sets the records to exactly what I want them to be, so problem solved for now.
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
Hierarchical Summation of Parent Child in C#
I have the following model class Entry { public int Id { get; set; } public bool IsGroup { get; set; } public int? ParentId { get; set; } public List<YearCost> YearCost { get; set; } = new List<YearCost>(); } class YearCost { public int Year { get; set; } public decimal Cost { get; set; } } i have this sample list populated using the models above static void Main(string[] args) { var entries = new List<Entry> { new Entry { Id = 1, ParentId = null, IsGroup = true, }, new Entry { Id = 2, ParentId = 1, IsGroup = false, YearCost = new List<YearCost> { new YearCost { Year = 2019, Cost = 10 }, new YearCost { Year = 2020, Cost = 10 } } }, new Entry { Id = 3, ParentId = 1, IsGroup = true }, new Entry { Id = 4, ParentId = 3, IsGroup = true }, new Entry { Id = 5, ParentId = 4, IsGroup = false, YearCost = new List<YearCost> { new YearCost { Year = 2019, Cost = 15 }, new YearCost { Year = 2020, Cost = 10 } } }, new Entry { Id = 6, ParentId = 4, IsGroup = false, YearCost = new List<YearCost> { new YearCost { Year = 2019, Cost = 15 }, new YearCost { Year = 2020, Cost = 10 } } }, new Entry { Id = 7, ParentId = 3, IsGroup = true }, new Entry { Id = 8, ParentId = 7, IsGroup = false, YearCost = new List<YearCost> { new YearCost { Year = 2019, Cost = 30 }, new YearCost { Year = 2020, Cost = 30 } } }, new Entry { Id = 9, ParentId = 7, IsGroup = false, YearCost = new List<YearCost> { new YearCost { Year = 2019, Cost = 20 }, new YearCost { Year = 2020, Cost = 20 } } }, new Entry { Id = 10, ParentId = 3, IsGroup = false, YearCost = new List<YearCost> { new YearCost { Year = 2019, Cost = 5 }, new YearCost { Year = 2020, Cost = 5 } } }, }; Console.WriteLine(String.Format("{0,10}{1,10}{2,10}{3, 10}{4, 10}", "Id", "Group", "Parent Id", 2019, 2020)); Console.WriteLine(String.Format("{0,10}{1,10}{2,10}{3, 10}{4, 10}", "--", "-----", "---------", "----", "----")); foreach (var entry in entries.OrderBy(x=>x.ParentId)) { Console.Write(String.Format("{0,10}{1,10}{2,10}", entry.Id, entry.IsGroup ? "yes" : "no", entry.ParentId?.ToString() ?? "NULL", 2019, 2020)); foreach (var y in entry.YearCost) Console.Write(String.Format("{0,10}", y.Cost)); Console.WriteLine("\n"); } } Rule #1: only entry which is not a group has cost values entered manually by user while the group entry cost is calculated Rule #2: nesting of groups are allowed. what i want is to do hierarchical summation for each group as shown in the table below the value inside the square brackets has to be calculated. Id Group Parent Id 2019 2020 -- ----- --------- ---- ---- 1 yes NULL [95] [85] 2 no 1 10 10 3 yes 1 [85] [75] 4 yes 3 [30] [20] 7 yes 3 [50] [50] 10 no 3 5 5 5 no 4 15 10 6 no 4 15 10 8 no 7 30 30 9 no 7 20 20 Thanks in Advance
I've managed finally to have the answer first you need to group element by parent var groups = entries.ToLookup(x => x.ParentId).ToDictionary(x => x.Key ?? 0, x => x.ToArray().Select(e => e.Id).ToList()); then get all children helpers private List<int> GetAllChildren(int? parent, Dictionary<int, List<int>> groups) { List<int> children = new List<int>(); PopulateChildren(parent, children, groups); return children; } private void PopulateChildren(int? parent, List<int> children, Dictionary<int, List<int>> groups) { List<int> myChildren; if (groups.TryGetValue(parent.Value, out myChildren)) { children.AddRange(myChildren); foreach (int child in myChildren) { PopulateChildren(child, children, groups); } } } Then Iterate over the list to populate the totals foreach (var item in entries) { if (item.IsGroup) { var children = GetAllChildren(item.Id, groups); children.ForEach(c => { var entry = entries.FirstOrDefault(x => x.Id == c); if(entry != null) { if (!item.isGroup) { entry.YearCosts?.ForEach(y => { if (item.YearCosts.FirstOrDefault(yx => yx.Year == y.Year) == null) { item.YearCosts.Add(new YearCost { Year = y.Year, Cost = 0 }); } item.YearCosts.FirstOrDefault(yx => yx.Year == y.Year).Cost += y.Cost ?? 0; item.SubTotal += y.Cost ?? 0; }); } } }); } }
Foreign key between tbls
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"); /*******************************************************************************/
How to insert multiple RadioButtonFor value into database
I want to insert 3 value of radio button into Database using MVC. User need to select one material for each categories(Walls,Roof,Floor) Currently the user can only select one value (may need to do grouping).But when I do grouping only the structInfo value is inserted into database. I need all the 3 value inserted into database. This is how the database design look like the struct inf(walls,roof,floor) the materialinfo is (bricks.concrete,woods, etc) So can I make all the 3 value choosed by user save into database? This is my view #foreach (var structIN in Model.structInfo) { if (structIN.structId.Equals(1)) { #Html.Label(structIN.structNm) #: foreach (var material in Model.materialInfo) { if (material.materialId.Equals(1) || material.materialId.Equals(2) || material.materialId.Equals(3)) { #Html.RadioButtonFor(model => model.buildInfo.materialId, material.materialId)#Html.Label(material.materialNm) #Html.HiddenFor(model => model.buildInfo.structId, new { Value = structIN.structId }) } } } else if(structIN.structId.Equals(2)) { <br /> #Html.Label(structIN.structNm) #: foreach (var material2 in Model.materialInfo) { if (material2.materialId.Equals(2) || material2.materialId.Equals(4) || material2.materialId.Equals(5)) { #Html.RadioButtonFor(model2 => model2.buildInfo.materialId, material2.materialId)#Html.Label(material2.materialNm) #Html.HiddenFor(model2 => model2.buildInfo.structId, new { Value = structIN.structId }) } } } else if (structIN.structId.Equals(3)) { <br /> #Html.Label(structIN.structNm) #: foreach (var material3 in Model.materialInfo) { if (material3.materialId.Equals(6) || material3.materialId.Equals(3)) { #Html.RadioButtonFor(model3 => model3.buildInfo.materialId, material3.materialId) #Html.Label(material3.materialNm) #Html.HiddenFor(model3 => model3.buildInfo.structId, new { Value = structIN.structId }) } } } }
my GET method [HttpGet] public ActionResult RegisterForm() { PopulateStructMaterialData(); using (var dataBase = new TMXEntities()) { var model = new RegisterInfoPA() { //OTHER CODES }; return View(model); } } Populating Data private void PopulateStructMaterialData() { var list = new List<strucMaterial> { new strucMaterial{ifOthers = "", materialId = 1, materialNm = "Bricks", structId = 1, structNm = "Walls", insuranceReqId = 0, isSelected = false}, new strucMaterial{ifOthers = "", materialId = 2, materialNm = "Concrete", structId = 1, structNm = "Walls", insuranceReqId = 0, isSelected = false}, new strucMaterial{ifOthers = "", materialId = 3, materialNm = "Woods", structId = 1, structNm = "Walls", insuranceReqId = 0, isSelected = false}, new strucMaterial{ifOthers = "", materialId = 2, materialNm = "Concrete", structId = 2, structNm = "Roof", insuranceReqId = 0, isSelected = false}, new strucMaterial{ifOthers = "", materialId = 4, materialNm = "Tiles", structId = 2, structNm = "Roof", insuranceReqId = 0, isSelected = false}, new strucMaterial{ifOthers = "", materialId = 5, materialNm = "Zinc", structId = 2, structNm = "Roof", insuranceReqId = 0, isSelected = false}, new strucMaterial{ifOthers = "", materialId = 3, materialNm = "Woods", structId = 3, structNm = "Floor", insuranceReqId = 0, isSelected = false}, new strucMaterial{ifOthers = "", materialId = 6, materialNm = "Reinforced Concrete", structId = 3, structNm = "Floor", insuranceReqId = 0, isSelected = false}, }; ViewBag.populatebuilding = list; } In View List<Insurance.ViewModels.strucMaterial> viewModelSM = ViewBag.populatebuilding; for(int i=0; i<viewModelSM.Count; i++) { #Html.DisplayFor(m => viewModelSM[i].structNm) #Html.HiddenFor(m => viewModelSM[i].structId) #Html.CheckBoxFor(m => viewModelSM[i].isSelected) #Html.HiddenFor(m => viewModelSM[i].materialId) #Html.Label(viewModelSM[i].materialNm) } My POST method [HttpPost] public ActionResult RegisterForm(RegisterInfoPA viewmodel, List<strucMaterial> list) { using (var dataBase = new TMXEntities()) { var model = new RegisterInfoPA() { //OTHER CODES }; if (ModelState.IsValid) { //OTHER CODES var register = viewmodel.reg; var personalinfo = viewmodel.pinfo; //Save Register db.registers.Add(register); db.SaveChanges(); //Retriving required Id's var getid = register.registrationId; var getRegTypeID = register.regisTypeId; //SAVE PERSONAL INFO personalinfo.registrationId = getid; db.personalInfoes.Add(personalinfo); db.SaveChanges(); //---HOW SHOULD I SAVE THE CHECKBOX HERE?----------- **> tHIS IS MY CODE, BUT IT IS NOT WORKING** foreach(var item in list) (<< error starts here) { buildingInfo.materialId = item.materialId; buildingInfo.structId = item.structId; buildingInfo.insuranceReqId = item.insuranceReqId; db.buildingInfoes.Add(buildingInfo); } db.SaveChanges(); } } } I am always getting this error System.NullReferenceException: Object reference not set to an instance of an object. How the proper code should look like? Thank you.
Multiple setups for a mockset ASP.net only carries out 1 mock
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);