code first with different entities - asp.net-mvc-4

I have three model classes and three views. Models are given below
public class BASLPApplicationFormModel
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int BASLPApplicationID { get; set; }
public string BASLPApplicationNo { get; set; }
public string ApplicantName { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Date of Birth", Prompt = "DD/MM/YYYY")]
public DateTime DateOfBirth { get; set; }
[Required]
[Display(Name = "Email-ID")]
public string EmailID { get; set; }
}
and second
public class DPPHIApplicationFormModel
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int DPPHIApplicationID { get; set; }
public string DPPHIapplicationNo { get; set; }
[Required]
[Display(Name = "Name of Applicant")]
[DataType(DataType.Text)]
public string Name { get; set; }
[Required]
[Display(Name = "Expansion of Initial")]
[DataType(DataType.Text)]
public string InitialExpansion { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Date of Birth", Prompt = "MM/DD/YYYY")]
public DateTime DateOfBirth { get; set; }
[Required]
[Display(Name = "Email-ID")]
[DataType(DataType.EmailAddress)]
public string EmailID { get; set; }
}
and third
public class DTYDHHApplicationFormModel
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int DTYDHHApplicationID { get; set; }
public string DTYDHHAapplicationNo { get; set; }
[Required]
[Display(Name = "Name of Applicant")]
[DataType(DataType.Text)]
public string name { get; set; }
[RegularExpression("^([0-9]+)$", ErrorMessage = "Invalid Phone Number")]
[DataType(DataType.PhoneNumber)]
[Display(Name = "Land Line Number")]
public string Phone { get; set; }
[Required]
[Display(Name = "Email-ID")]
[DataType(DataType.EmailAddress)]
public string EmailID { get; set; }
}
Email model ,
[Table("Emails")]
public class UserEmails
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string UserEmailID { get; set; }
}
Here user interacts with any of the forms and submitting their forms accordingly.
I would like to get all Email entries to my Emails table using code first approach and please advice me how can achieve.

Take a look at this serie of three blogposts:
http://weblogs.asp.net/manavi/archive/2010/12/24/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-1-table-per-hierarchy-tph.aspx
http://weblogs.asp.net/manavi/archive/2010/12/28/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-2-table-per-type-tpt.aspx
http://weblogs.asp.net/manavi/archive/2010/12/24/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-1-table-per-hierarchy-tph.aspx
Hope this helps

Related

Blazor validation not working when using Metadata class

I am using blazore Server side. Form validation is not working when using Metadata class. I am using scaffolding and my DB models are oftern automatically generated. If i modify the it wipes out all my Dataannotation validations.
Here is the class that i am using
public partial class RequestHelp
{
public Guid ID { get; set; }
public Guid UserID { get; set; }
public string HelpFor { get; set; }
public string TypeOfHelp { get; set; }
public string Description { get; set; }
public DateTime UTCDateCreated { get; set; }
public DateTime UTCLastUpdateDate { get; set; }
public string CurrencyCode { get; set; }
public decimal? Amount { get; set; }
public bool? IsDeleted { get; set; }
}
[MetadataType(typeof(RequestHelpMetaData))]
public partial class RequestHelp
{
}
public class RequestHelpMetaData
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid ID { get; set; }
[Required(ErrorMessage = "Please select Who needs Help.")]
public string HelpFor { get; set; }
[Required(ErrorMessage = "Please select What kind of Help you are Requesting.")]
public string TypeOfHelp { get; set; }
[Required(ErrorMessage = "Please Currency.")]
public string CurrencyCode { get; set; }
[Required(ErrorMessage = "Amount Field is required")]
[Range(1, 999999999999999, ErrorMessage = "Please enter positive number")]
public decimal? Amount { get; set; }
[Required(ErrorMessage = "Please enter Details about what you need help for.")]
[StringLength(4000,MinimumLength=10, ErrorMessage = "Please eneter some details about the help you need")]
public string Description { get; set; }
}
}
This is how i am using it in blazor.
<EditForm Model="#_requesForHelp" OnValidSubmit="#HandleValidSubmit">
<DataAnnotationsValidator />
<ValidationSummary />
</EditForm>

The ForeignKeyAttribute on property 'FontNameId' on type 'ConferenceManagementSystem.Models.FontName' is not valid

New to the website here, and I had tried several solutions which solved similar problems but to no avail, so would really appreciate for some help.
The error:
The ForeignKeyAttribute on property 'FontNameId' on type 'ConferenceManagementSystem.Models.FontName' is not valid. The navigation property 'AbstractFileFormat' was not found on the dependent type 'ConferenceManagementSystem.Models.FontName'. The Name value should be a valid navigation property name.
The code snippet:
namespace ConferenceManagementSystem.Models
{
[Table("AbstractFileFormat")]
public class AbstractFileFormat
{
[Key]
public int AbstractFileFormatId { get; set; }
[Required]
public string Title_HorizontalAlignment { get; set; }
[Required]
[ForeignKey("FontNameId")]
public int Title_FontName { get; set; }
[Required]
public string Title_FontSize { get; set; }
[Required]
public bool Title_Bold { get; set; }
[Required]
public bool Title_Italic{ get; set; }
[Required]
public string Name_HorizontalAlignment { get; set; }
[Required]
[ForeignKey("FontNameId")]
public int Name_FontName { get; set; }
[Required]
public string Name_FontSize { get; set; }
[Required]
public bool Name_Bold { get; set; }
[Required]
public bool Name_Italic { get; set; }
[Required]
public string Address_HorizontalAlignment { get; set; }
[Required]
[ForeignKey("FontNameId")]
public int Address_FontName { get; set; }
[Required]
public string Address_FontSize { get; set; }
[Required]
public bool Address_Bold { get; set; }
[Required]
public bool Address_Italic { get; set; }
[Required]
public string Email_HorizontalAlignment { get; set; }
[Required]
[ForeignKey("FontNameId")]
public int Email_FontName { get; set; }
[Required]
public string Email_FontSize { get; set; }
[Required]
public bool Email_Bold { get; set; }
[Required]
public bool Email_Italic { get; set; }
public float LineSpacing { get; set; }
public int ConferenceId { get; set; }
public virtual Conference Conference { get; set; }
public virtual FontName FontName { get; set; }
}
}
Second snippet:
namespace ConferenceManagementSystem.Models
{
[Table("FontName")]
public class FontName
{
[Key]
public int FontNameId { get; set; }
public int Name { get; set; }
public virtual ICollection<AbstractFileFormat> AbstractFileFormats { get; set; }
}
}
I had the same issue, and I did this, and it worked.
Add another property in AbstractFileFormat class, that corresponds to the Foreign Key in the AbstractFileFormat table. i.e. the field that points to the FontNameId field in the FontName table. Something like this:
public int FontNameId { get; set; }
[Required]
[ForeignKey("FontNameId")]
public int Email_FontName { get; set; }

The field must be a Date

I have a situation with data field validation in MVC 4
this is my Model
public class Purchase
{
public Purchase()
{
PurchaseDetails = new List<PurchaseDetails>();
}
public int PurchaseID { get; set; }
[DisplayName("Compra N°")]
[Required]
public int PurchaseNumber { get; set; }
[DisplayName("Anulada")]
[Required]
public bool isAnulada { get; set; }
public int ProviderID { get; set; }
public virtual Provider Provider { get; set; }
[DisplayName("Nombres/Notas")]
[Required]
public string Notes { get; set; }
[DisplayName("Detalles de Compra")]
public string ProposalDetails { get; set; }
[DataType(DataType.Date), DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
[DisplayName("Creado")]
public DateTime TimeStamp { get; set; }
[DataType(DataType.Date), DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
[DisplayName("Pagado en Fecha")]
public DateTime PaidDate { get; set; }
[DisplayName("Impuesto a la Compra")]
[Range(0.00, 100.0, ErrorMessage = "Valor debe estar expresado en % Entre 0 y 100")]
public decimal AdvancePaymentTax { get; set; }
[DisplayName("Pagada")]
[Required]
public bool Paid { get; set; }
public virtual ICollection<PurchaseDetails> PurchaseDetails { get; set; }
}
When try Post or Create my purchase raise the error "The Field must be a Date" i don't know how, this malfunction appear in IExplorer an Chrome browser
Any Idea? Thanks for the answer....

How to post model with kendo window refresh?

How to pass model with Kendo Window refresh option ?
I am using below code for that in my partial view:-
var proWindow = $("#productWindow").data("kendoWindow");
proWindow.refresh({
url: "../../Product/UpdateProduct",
type: "POST",
contentType:"application/json",
data: { prodModel: $("form").serialize()
});
And below is the code for Controller:-
[HttpPost]
public ActionResult UpdateProduct(ProductMaintViewModel prodModel)
{
}
But i am getting null on my model parameter in controller.
Can any one have any idea about that,means how we can post the whole model with kendo window refresh data option in jquery/javascript ?
FYI, i am working on ASP.NET MVC 4 application.
Below is my ProductMaintViewModel class :-
public class ProductMaintViewModel
{
[HiddenInput(DisplayValue = false)]
public int ProductID { get; set; }
public int? CustomerId { get; set; }
public int? InsuranceId { get; set; }
[Required]
[StringLength(50)]
[Remote("CheckProductName", "Product", ErrorMessage = "Product Name already exists.")]
[Display(Name = "Name")]
public string Name { get; set; }
[StringLength(100)]
[Display(Name = "Description")]
public string Description { get; set; }
public bool IsDraft { get; set; }
[Required]
[Display(Name = "Product Type")]
public int? SelectedProductTypeID { get; set; }
public IEnumerable<SelectListItem> ProductTypes { get; set; }
public bool IsDeleted { get; set; }
[Display(Name = "Customer Type")]
public int? SelectedCustomerSubTypeId { get; set; }
public IEnumerable<SelectListItem> CustomerSubTypes { get; set; }
public IEnumerable<SelectListItem> AvailableLabor { get; set; }
}

how I define my model using lazyloading = true

How I define my model using lazyloading = true in MVC 4? I am trying to load my foreign keys. Now my query is coming null. In my web api query comes right.
I did not use the "virtual".
My Model:
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int intClienteFornecedorId { get; set; }
[MaxLength(50)]
[Display(Name = "Nome:")]
[UniqueClienteFornecedorNome(ErrorMessage = "Já existe um Cliente ou Fornecedor cadastrado com esse Nome.")]
[Required(ErrorMessage = "É obrigatório informar o Nome.")]
public string strClienteFornecedorNome { get; set; }
[MaxLength(2)]
[Display(Name = "Pessoa:")]
public string strClienteFornecedorPessoa{ get; set; }
[ForeignKey("Estado")]
[Display(Name = "Estado:")]
public string strUFId { get; set; }
public virtual Estado Estado { get; set; }
[MaxLength(9)]
[Display(Name = "CEP:")]
public string strClienteFornecedorCEP { get; set; }
[MaxLength(70)]
[Display(Name = "Site:")]
public string strClienteFornecedorSite { get; set; }
[MaxLength(250)]
[Display(Name = "Observação:")]
public string strClienteFornecedorObservacao { get; set; }
[MaxLength(1)]
[Display(Name = "Situação:")]
public string strClienteFornecedorSituacao { get; set; }
[ForeignKey("Usuario")]
public int intUsuarioId { get; set; }
public virtual Usuario Usuario { get; set; }
public DateTime? dtClienteFornecedorDataAlteracao { get; set; }
public DateTime? dtClienteFornecedorDataCriacao { get; set; }
[NotMapped]
public bool ckbClienteFornecedor { get; set; }
[NotMapped]
public bool? hdMaisInformacoes { get; set; }
[NotMapped]
public bool? hdObservacao { get; set; }
public virtual ICollection<Contato> Contatos { get; set; }
public virtual ICollection<ClienteFornecedor_Contato> ClienteFornecedoresContatos { get; set; }
WEB API:
[System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, false)]
public List<ClienteFornecedor> GetClientesFornecedoresByintUsuarioId(int intUsuarioId)
{
//Validate Input
if (intUsuarioId.IsEmpty())
return GetAllClienteFornecedor();
_DatabaseContext.ContextOptions.LazyLoadingEnabled = false;
return (from clienteFornecedor in _DatabaseContext.ClienteFornecedor
where clienteFornecedor.intUsuarioId == intUsuarioId
select clienteFornecedor).Include("Usuario").Include("UF").OrderBy(c => c.strClienteFornecedorNome).ToList();
}
In the web api returns two records, but in my web application the second record returns null why?
Could anyone help me please?
The second record is null, anyone know why?
JSON:
[{"$id":"1","intClienteFornecedorId":8,"strClienteFornecedorNome":"CPFL","strClienteFornecedorPessoa":"PJ","strClienteFornecedorCPF":null,"strClienteFornecedorCNPJ":"11.111.111/1111-11","strClienteFornecedorTelefone":null,"strClienteFornecedorTelefone2":null,"strClienteFornecedorEmail":null,"strClienteFornecedorEndereco":null,"strClienteFornecedorComplemento":null,"strClienteFornecedorBairro":null,"strClienteFornecedorCidade":"SP","strUFId":"SP","strClienteFornecedorCEP":null,"strClienteFornecedorSite":null,"strClienteFornecedorObservacao":null,"strClienteFornecedorSituacao":"A","intUsuarioId":1,"dtClienteFornecedorDataAlteracao":"2013-10-30T11:29:33.303","dtClienteFornecedorDataCriacao":"2013-10-30T11:29:33.303","Categoria":[],"UF":{"$id":"2","strUFId":"SP","strUFNome":"São Paulo","Contato":[],"ClienteFornecedor":[{"$ref":"1"}],"EntityKey":{"$id":"3","EntitySetName":"UF","EntityContainerName":"DatabaseContext","EntityKeyValues":[{"Key":"strUFId","Type":"System.String","Value":"SP"}]}},"Usuario":{"$id":"4","intUsuarioId":1,"strUsuarioNome":"Danielle Ramos Tonhai","strUsuarioEmail":"danielle.ramos#unidax.com.br","strUsuarioSenha":"12345678","strUsuarioAdministrador":"S","strUsuarioSituacao":"A","intUsuarioPaiId":0,"dtUsuarioDataAlteracao":"2013-10-28T15:16:28.233","dtUsuarioDataCriacao":"2013-10-24T16:42:26","bitUsuarioConfirmado":true,"CartaoCredito":[],"Categoria":[],"ContaBancaria":[],"ContaContabil":[],"Contato":[],"Entidade":[],"Evento":[],"FormaPagamento":[],"ClienteFornecedor":[{"$ref":"1"},{"$id":"5","intClienteFornecedorId":9,"strClienteFornecedorNome":"Danielle","strClienteFornecedorPessoa":"PF","strClienteFornecedorCPF":"111.111.111-11","strClienteFornecedorCNPJ":null,"strClienteFornecedorTelefone":null,"strClienteFornecedorTelefone2":null,"strClienteFornecedorEmail":null,"strClienteFornecedorEndereco":null,"strClienteFornecedorComplemento":null,"strClienteFornecedorBairro":null,"strClienteFornecedorCidade":null,"strUFId":null,"strClienteFornecedorCEP":null,"strClienteFornecedorSite":null,"strClienteFornecedorObservacao":null,"strClienteFornecedorSituacao":"A","intUsuarioId":1,"dtClienteFornecedorDataAlteracao":"2013-10-30T11:29:52.203","dtClienteFornecedorDataCriacao":"2013-10-30T11:29:52.203","Categoria":[],"UF":null,"Usuario":{"$ref":"4"},"Contato":[],"EntityKey":{"$id":"6","EntitySetName":"ClienteFornecedor","EntityContainerName":"DatabaseContext","EntityKeyValues":[{"Key":"intClienteFornecedorId","Type":"System.Int32","Value":"9"}]}}],"EntityKey":{"$id":"7","EntitySetName":"Usuario","EntityContainerName":"DatabaseContext","EntityKeyValues":[{"Key":"intUsuarioId","Type":"System.Int32","Value":"1"}]}},"Contato":[],"EntityKey":{"$id":"8","EntitySetName":"ClienteFornecedor","EntityContainerName":"DatabaseContext","EntityKeyValues":[{"Key":"intClienteFornecedorId","Type":"System.Int32","Value":"8"}]}},{"$ref":"5"}]