I have a Contractor class and a Musicians Class which inherits the Contractor class. I am running migration and it will only build one Contractor table with Musicians fields included. I want a Contractor table and Musicians table that follows my domain models. It creates Instrument table correctly. Does this have something to do with the fact I am using inheritance on the classes?
public class Contractor
{
public Guid ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string ZipCode { get; set; }
public string Phone { get; set; }
public string Description { get; set; }
[DataType(DataType.Date)]
public DateTime CreateDate { get; set; }
[DataType(DataType.Date)]
public DateTime SuspendDate { get; set; }
public byte[] ImageData { get; set; }
public string ImageMimeType { get; set; }
public string ImageName { get; set; }
public bool Suspended { get; set; }
}
public class Musician : Contractor
{
public Guid MusiciansId { get; set; }
public string WebsiteLink { get; set; }
public string YouTubeLink { get; set; }
public string SoundCloudLink { get; set; }
public string ReverbNationLink { get; set; }
public int YearsOfExperience { get; set; }
[DataType(DataType.Date)]
public DateTime NextDateAvailable { get; set; }
public Instrument Instrument { get; set; }
public int InstrumentId { get; set; }
public Contractor Contractor { get; set; }
public Guid ContractorId { get; set; }
}
My Migration script :
CreateTable(
"dbo.Contractor",
c => new
{
ID = c.Guid(nullable: false),
FirstName = c.String(),
LastName = c.String(),
Email = c.String(),
ZipCode = c.String(),
Phone = c.String(),
Description = c.String(),
CreateDate = c.DateTime(nullable: false),
SuspendDate = c.DateTime(nullable: false),
ImageData = c.Binary(),
ImageMimeType = c.String(),
ImageName = c.String(),
Suspended = c.Boolean(nullable: false),
UnionMember = c.Boolean(),
MusiciansId = c.Guid(),
WebsiteLink = c.String(),
YouTubeLink = c.String(),
SoundCloudLink = c.String(),
ReverbNationLink = c.String(),
YearsOfExperience = c.Int(),
NextDateAvailable = c.DateTime(),
InstrumentId = c.Int(),
ContractorId = c.Guid(),
Discriminator = c.String(nullable: false, maxLength: 128),
})
.PrimaryKey(t => t.ID)
.ForeignKey("dbo.Contractor", t => t.ContractorId)
.ForeignKey("dbo.Instrument", t => t.InstrumentId, cascadeDelete: true)
.Index(t => t.InstrumentId)
.Index(t => t.ContractorId);
It is not a good idea to use inheritance in model classes.
You can add Type value for your Contractor and create another table for each type of contractor (Musician for example):
public enum ContractorType
{
Musician = 0
}
public class Contractor
{
public Guid ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string ZipCode { get; set; }
public string Phone { get; set; }
public string Description { get; set; }
[DataType(DataType.Date)]
public DateTime CreateDate { get; set; }
[DataType(DataType.Date)]
public DateTime SuspendDate { get; set; }
public byte[] ImageData { get; set; }
public string ImageMimeType { get; set; }
public string ImageName { get; set; }
public bool Suspended { get; set; }
public ContractorType contractorType { get; set; }
public Musician Musician { get; set; }
}
After doing some research the answer is: [Table] attribute above Musicians class.
http://www.codeproject.com/Articles/796521/Inheritance-in-Entity-Framework-Table-Per-Type
Related
I know this question might be asked so many times, I tried a lot to find the answer and ultimately I am throwing it here if some one can help me.
I am doing a project in ASP.NET Core MVC with a database-first approach. I have a registration form where I need to populate Country and City dropdowns to fill with data coming in through WeCareConext class.
In my controller I am doing this:
[HttpGet]
public IActionResult Register()
{
CompanyEditViewModel model = new CompanyEditViewModel();
var fromDatabaseEF = new SelectList(_context.Country.ToList(), "CountryId", "NameEn");
ViewData["CompanyRegister"] = fromDatabaseEF;
return View(model);
}
My Country model:
public partial class Country
{
public Country()
{
City = new HashSet<City>();
Currency = new HashSet<Currency>();
HolidayType = new HashSet<HolidayType>();
Holidays = new HashSet<Holidays>();
Province = new HashSet<Province>();
StaffInfo = new HashSet<StaffInfo>();
}
public int CountryId { get; set; }
public string NameAr { get; set; }
public string NameEn { get; set; }
public string NameFr { get; set; }
public string IsoCode2 { get; set; }
public string IsoCode3 { get; set; }
public string RegionAr { get; set; }
public string Region { get; set; }
public byte? PostcodeRequired { get; set; }
public bool? IsActive { get; set; }
public byte? IsAvailable { get; set; }
public string MobileMask { get; set; }
public byte? IsDeleted { get; set; }
public int? BaseCharges { get; set; }
public int? MobileNumberLength { get; set; }
public string CountryCode { get; set; }
public byte[] IconImage { get; set; }
public string PickerListAr { get; set; }
public string PickerListEn { get; set; }
public string PickerListFr { get; set; }
public virtual ICollection<City> City { get; set; }
public virtual ICollection<Currency> Currency { get; set; }
public virtual ICollection<HolidayType> HolidayType { get; set; }
public virtual ICollection<Holidays> Holidays { get; set; }
public virtual ICollection<Province> Province { get; set; }
public virtual ICollection<StaffInfo> StaffInfo { get; set; }
}
My CompanyEditViewModel class:
public class CompanyEditViewModel
{
[Display(Name = "Company Number")]
public string CompanyId { get; set; }
[Required]
[Display(Name = "Company Name")]
[StringLength(75)]
public string Name { get; set; }
[Required]
[Display(Name = "Country")]
public string CountryId { get; set; }
public IEnumerable<SelectListItem> Countries { get; set; }
[Required]
[Display(Name = "City")]
public string SelectedCityCode { get; set; }
public IEnumerable<SelectListItem> Cities { get; set; }
}
Unfortunately, this returns an error:
System.ArgumentException: 'Format of the initialization string does not conform to specification starting at index 0.'
I am trying different approaches but not solving my issue. Can anyone suggest some code which can help me and I can also select country and then populate city dropdown according to the CountryID without page reload ? Thanks in advance.
I am using code-first Entity Framework in my ASP.NET MVC project
I have these tables
User
public class User:IBaseEntity
{
public User()
{
UserRoles = new List<UserRole>();
}
public int ID { get; set; }
public int RoleId { get; set; }
public string Email { set; get; }
public string Password { set; get; }
public string FirstName { set; get; }
public string LastName { set; get; }
public string Company { set; get; }
public string Address1 { set; get; }
public string Address2 { set; get; }
public string City { set; get; }
public string PostalCode { set; get; }
public string Country { set; get; }
public string State { set; get; }
public bool Active { set; get; }
public DateTime? CreatedOn { set; get; }
public DateTime? DeletedOn { set; get; }
public virtual ICollection<UserRole> UserRoles { get; set; }
}
Role
public class Role : IBaseEntity
{
public int ID { get; set; }
public string RoleName { get; set; }
public bool Active { set; get; }
public DateTime? CreatedOn { set; get; }
public DateTime? DeletedOn { set; get; }
}
UserRole
public class UserRole : IBaseEntity
{
public int ID { get; set; }
public int UserId { get; set; }
public int RoleId { get; set; }
public virtual Role Role { get; set; }
}
IBaseEntity
public interface IBaseEntity
{
int ID { get; set; }
}
I need seed data User with UserRole
How can I put UserRole in method create User?
public void CreateRoles(CMSDbContext context)
{
if (context.Roles.Count() == 0)
{
List< Role> listRole = new List<Role>()
{
new Role()
{
RoleName = "Admin",
Active = true,
CreatedOn = DateTime.Now
},
new Role()
{
RoleName = "User",
Active = true,
CreatedOn = DateTime.Now
}
};
context.Roles.AddRange(listRole);
context.SaveChanges();
}
}
public void CreateUser(CMSDbContext context)
{
if (context.Users.Count() == 0)
{
List<User> listUser = new List<User>()
{
new User()
{
FirstName = "David",
LastName = "Lima",
Active = true,
Email = "admin#domain.com",
Address1 = "New York",
Address2 = "Chicago",
Company = "Test",
CreatedOn = DateTime.Now,
PostalCode = "123456",
State = "Test",
City = "test",
UserRoles =???
Password = CMS.Common.HashMD5.CreateMD5("12356")
}
};
context.Users.AddRange(listUser);
context.SaveChanges();
}
}
}
Please focus on method CreateUser have property UserRole, not sure what I can put here. I also create some roles in Role table (admin, user)
I am getting stuck at this point.
Any help will be appreciated
Thanks all
I'm learning ASP.NET MVC 4 with Entity Framework (Database First) and ran into a problem that I'm not able to solve.
I have following tables:
Student: To store students information
Course: To store courses running in an institute
StudentCourse: To store which student selected what course
Fees: To store submitted fees by a student corresponding to StudentCourse
Now, I wan't to show course name, course fees, total fees submitted & the pending fees of students
I'm using Entity Framework in the project and trying to execute a query like this:
var feeslist = entities.Fees
.Where(m => m.StudentCourse.status=="pending")
.GroupBy(m => m.StudentCourse.id)
.Select(m => new { StudentCourseId = m.Key, SumOfFees = m.Sum(v => v.fees) });
I want to get Course object instead of StudentCourseId so that i can display the course, its course fees and total fees submitted by student.
In case, I'm listing all of the four class contents:
Student
public partial class Student
{
public Student()
{
this.Leaves = new HashSet<Leave>();
this.StudentCourses = new HashSet<StudentCourse>();
}
public int id { get; set; }
public string first_name { get; set; }
public string middle_name { get; set; }
public string last_name { get; set; }
public string password { get; set; }
public string email { get; set; }
public string gender { get; set; }
public string facebook { get; set; }
public string contact_number { get; set; }
public string address { get; set; }
public string admin { get; set; }
public string college { get; set; }
public string status { get; set; }
public System.DateTime createdat { get; set; }
public System.DateTime updatedat { get; set; }
public string descripton { get; set; }
public virtual ICollection<Leave> Leaves { get; set; }
public virtual ICollection<StudentCourse> StudentCourses { get; set; }
}
Course
public partial class Course
{
public Course()
{
this.CourseContents = new HashSet<CourseContent>();
this.StudentCourses = new HashSet<StudentCourse>();
}
public int id { get; set; }
public string course_name { get; set; }
public int course_fees { get; set; }
public int duration { get; set; }
public string admin { get; set; }
public string status { get; set; }
public System.DateTime createdat { get; set; }
public System.DateTime updatedat { get; set; }
public virtual ICollection<CourseContent> CourseContents { get; set; }
public virtual ICollection<StudentCourse> StudentCourses { get; set; }
}
StudentCourse
public partial class StudentCourse
{
public StudentCourse()
{
this.Fees1 = new HashSet<Fee>();
this.Issues = new HashSet<Issue>();
}
public int id { get; set; }
public int student_id { get; set; }
public int course_id { get; set; }
public int fees { get; set; }
public System.DateTime join_date { get; set; }
public string admin { get; set; }
public System.DateTime createdat { get; set; }
public System.DateTime updatedat { get; set; }
public string status { get; set; }
public virtual Course Course { get; set; }
public virtual ICollection<Fee> Fees1 { get; set; }
public virtual ICollection<Issue> Issues { get; set; }
public virtual Student Student { get; set; }
}
Fee
public partial class Fee
{
public int id { get; set; }
public int student_course_id { get; set; }
public int fees { get; set; }
public string admin { get; set; }
public System.DateTime createdat { get; set; }
public System.DateTime updatedat { get; set; }
public virtual StudentCourse StudentCourse { get; set; }
}
var feeslist = entities.Fees
.Where(m => m.StudentCourse.status=="pending")
.GroupBy(m => m.StudentCourse.Course)
.Select(m => new { Course = m.Key, SumOfFees = m.Sum(v => v.fees) });
I have a View model
public class TrainingProgramScheduledDateVM
{
public bool IsTuesday { get; set; }
[DataType(DataType.Time)]
public string TueStartTime { get; set; }
[DataType(DataType.Time)]
public string TueEndTime { get; set; }
public bool IsWednesday { get; set; }
[DataType(DataType.Time)]
public string WedStartTime { get; set; }
[DataType(DataType.Time)]
public string WedEndTime { get; set; }
public bool IsThursday { get; set; }
[DataType(DataType.Time)]
public string ThuStartTime { get; set; }
[DataType(DataType.Time)]
public string ThuEndTime { get; set; }
}
I want to put the validation i a way that.
1- If IsTuesday = true Then TueStartTime and TueEndTime should Requires.
and so on for other
2- At least one boolean value should be true and relevant time should be required.
please suggest me any easy way.
Thanks
Use remote validation. For example, Here
[Remote(
"doesProductNameExistUnderCategory",
"Northwind",
AdditionalFields = "Category_ID",
ErrorMessage = "Product name already exists under the chosen category. Please enter a different product name.",
HttpMethod = "POST"
)]
[Required]
public string Product_Name { get; set; }
I see repetition. This block:
public bool IsTuesday { get; set; }
[DataType(DataType.Time)]
public string TueStartTime { get; set; }
[DataType(DataType.Time)]
public string TueEndTime { get; set; }
Can better be abstracted into its own type, like:
public class ScheduleDate
{
public DayOfWeek DayOfWeek { get; set; }
public bool IsSelected { get; set; }
[DataType(DataType.Time)]
[RequiredIf(IsSelected)]
public string StartTime { get; set; }
[DataType(DataType.Time)]
[RequiredIf(IsSelected)]
public string EndTime { get; set; }
}
Then your TrainingProgramScheduledDateVM can contain a list of ScheduleDate objects.
I'm working on a MVC Web Site and as i'm newbie in mvc i'm facing some issues. This one is realy weird and have been bothering me for a while. I'm using LINQ to make my queries and some of then were realy, realy slow.
Then i opened SQL Server Profiler to look for the queries on a closer way. I just noted that my LINQ queries are being sent to the database without the where clause and that is making then to take a long time to be executed.
Now i'll post relevant part of code to see if u guys can get something wrong with that.
Model
[Table("tblSolicitacao")]
public partial class ChamadosViewModel
{
[Key]
public int Nsu { get; set; }
[Required(ErrorMessage = "*")]
public int IdAutor { get; set; }
[Required(ErrorMessage = "*")]
[DisplayName("Assunto")]
public string NomeDaSolicitacao { get; set; }
[Required(ErrorMessage = "*")]
[DisplayName("Descrição")]
public string Descricao { get; set; }
[Required(ErrorMessage = "*")]
[DisplayName("Grupo")]
public string Grupo { get; set; }
[Required(ErrorMessage = "*")]
[DisplayName("Atividade")]
public string Atividade { get; set; }
[Required(ErrorMessage = "*")]
[DisplayName("Prioridade")]
public string Prioridade { get; set; }
[Required(ErrorMessage = "*")]
[DataType(DataType.DateTime, ErrorMessage = "Formato de Data Inválido")]
public Nullable<System.DateTime> DataPretendidaPeloAutor { get; set; }
public Nullable<bool> AcompanharViaEmail { get; set; }
public Nullable<int> IdAnalistaDesignado { get; set; }
public string Complexidade { get; set; }
public Nullable<System.DateTime> DataPrevistaPeloAnalista { get; set; }
public Nullable<int> SubordinacaoDeSolicitacao { get; set; }
public string COD_FORNECEDOR { get; set; }
public Nullable<decimal> TOLERANCIA { get; set; }
public string DESC_COND_PGTO { get; set; }
public string FILIAL_FATURAR { get; set; }
public string FILIAL_ENTREGA { get; set; }
public string FILIAL_COBRANCA { get; set; }
public string MOTIVO_COMPRA { get; set; }
public Nullable<int> TIPO_SOLICITACAO { get; set; }
public string FORMA_PGTO { get; set; }
public string MOTIVOCHAMADO { get; set; }
public Nullable<int> TEMPORESOLUCAO { get; set; }
public string CodigoRateioFilial { get; set; }
public string CodigoRateioCentroCusto { get; set; }
public Nullable<System.DateTime> DataSolicitacao { get; set; }
[NotMapped]
public string NomeAutor { get; set; }
[NotMapped]
public string NomeAnalista { get; set; }
public IEnumerable<genericoGruposViewModel> Grupos { get; set; }
[NotMapped]
public List<ListItem> Transitos { get; set; }
public List<string> Complexidades { get; set; }
public IEnumerable<genericoGrupoAtividadeViewModel> Atividades { get; set; }
public IEnumerable<genericoPrioridadeViewModel> Prioridades { get; set; }
public IEnumerable<ColaboradorViewModel> Usuarios { get; set; }
[NotMapped]
IEnumerable<ColaboradorViewModel> AnalistasDesignados { get; set; }
}
Controller
ChamadosViewModel ChamadoDetalhe = new ChamadoDetalhe();
ChamadoDetalhe = _dbHelpDesk.Chamados
.ToList()
.Where(x => x.Nsu == NumeroChamado)
.Select(x => new ChamadosViewModel
{
Nsu = x.Nsu,
IdAutor = x.IdAutor,
NomeDaSolicitacao = x.NomeDaSolicitacao,
Descricao = x.Descricao,
Grupo = x.Grupo,
Atividade = x.Atividade,
Prioridade = x.Prioridade,
DataPretendidaPeloAutor = x.DataPretendidaPeloAutor,
AcompanharViaEmail = x.AcompanharViaEmail,
IdAnalistaDesignado = x.IdAnalistaDesignado,
Complexidade = x.Complexidade,
DataPrevistaPeloAnalista = x.DataPrevistaPeloAnalista,
SubordinacaoDeSolicitacao = x.SubordinacaoDeSolicitacao,
COD_FORNECEDOR = x.COD_FORNECEDOR,
TOLERANCIA = x.TOLERANCIA,
DESC_COND_PGTO = x.DESC_COND_PGTO,
FILIAL_FATURAR = x.FILIAL_FATURAR,
FILIAL_ENTREGA = x.FILIAL_ENTREGA,
FILIAL_COBRANCA = x.FILIAL_COBRANCA,
MOTIVO_COMPRA = x.MOTIVO_COMPRA,
TIPO_SOLICITACAO = x.TIPO_SOLICITACAO,
FORMA_PGTO = x.FORMA_PGTO,
MOTIVOCHAMADO = x.MOTIVOCHAMADO,
TEMPORESOLUCAO = x.TEMPORESOLUCAO,
CodigoRateioFilial = x.CodigoRateioFilial,
CodigoRateioCentroCusto = x.CodigoRateioCentroCusto,
DataSolicitacao = x.DataSolicitacao
}
)
.Single()
and thats the select that went to the database
SELECT
[Extent1].[Nsu] AS [Nsu],
[Extent1].[IdAutor] AS [IdAutor],
[Extent1].[NomeDaSolicitacao] AS [NomeDaSolicitacao],
[Extent1].[Descricao] AS [Descricao],
[Extent1].[Grupo] AS [Grupo],
[Extent1].[Atividade] AS [Atividade],
[Extent1].[Prioridade] AS [Prioridade],
[Extent1].[DataPretendidaPeloAutor] AS [DataPretendidaPeloAutor],
[Extent1].[AcompanharViaEmail] AS [AcompanharViaEmail],
[Extent1].[IdAnalistaDesignado] AS [IdAnalistaDesignado],
[Extent1].[Complexidade] AS [Complexidade],
[Extent1].[DataPrevistaPeloAnalista] AS [DataPrevistaPeloAnalista],
[Extent1].[SubordinacaoDeSolicitacao] AS [SubordinacaoDeSolicitacao],
[Extent1].[COD_FORNECEDOR] AS [COD_FORNECEDOR],
[Extent1].[TOLERANCIA] AS [TOLERANCIA],
[Extent1].[DESC_COND_PGTO] AS [DESC_COND_PGTO],
[Extent1].[FILIAL_FATURAR] AS [FILIAL_FATURAR],
[Extent1].[FILIAL_ENTREGA] AS [FILIAL_ENTREGA],
[Extent1].[FILIAL_COBRANCA] AS [FILIAL_COBRANCA],
[Extent1].[MOTIVO_COMPRA] AS [MOTIVO_COMPRA],
[Extent1].[TIPO_SOLICITACAO] AS [TIPO_SOLICITACAO],
[Extent1].[FORMA_PGTO] AS [FORMA_PGTO],
[Extent1].[MOTIVOCHAMADO] AS [MOTIVOCHAMADO],
[Extent1].[TEMPORESOLUCAO] AS [TEMPORESOLUCAO],
[Extent1].[CodigoRateioFilial] AS [CodigoRateioFilial],
[Extent1].[CodigoRateioCentroCusto] AS [CodigoRateioCentroCusto],
[Extent1].[DataSolicitacao] AS [DataSolicitacao]
FROM [dbo].[tblSolicitacao] AS [Extent1]
Do you guys can imagine a reason for this where clause to have been omited ? Maybe something on my model class ?
Thanks for the support.
The ToList call brings the entire result set into memory and then you are performing the where, try the following:
dbHelpDesk.Chamados
.Where(x => x.Nsu == NumeroChamado)
.ToList()
.Select(x => new ChamadosViewModel ...
You used .ToList() before the .Where(.... .ToList() will grab the whole table in your situation. Simply remove that from your query and you should be good.