I have couple of entities such as Customer, Vendors, Employee and I have another entity to handle Transaction Head, check definition here:
public class TransactionHead
{
public string DocumentNo { get; set; }
public DocumentType TransactionType { get; set; }
public Location From { get; set; }
public object To { get; set; }//customer, supplier, location, employee "will have a discount table "
public DateTime DocumentDate { get; set; }
public float GrossAmount { get; set; }
public float TotalDiscount { get; set; }
public float NetAmount { get; set; }
public int DetailRowCount { get; set; }
public bool IsActive { get; set; }
public bool IsDeleted { get; set; }
public User Created { get; set; }
public User Updated { get; set; }
public User Approved { get; set; }
public DocumentStatus DocumentStatus { get; set; }
public string ApprovalRemark { get; set; }
public string DocumentRemark { get; set; }
public DateTime CreatedTimeStamp { get; set; }
public DateTime UpdatedTimeStamp { get; set; }
}
And now when I create migration, it automatically ignores the To property from TransactionHead entity. So what is the solution?
Thanks
No. EF doesn't support this because it would require dynamic column type in the database. the object property that EF will always ignore. you can find more information about complex type in EF in this link.
Related
I have two tables which have one-to-many relationship between them.
public class Policy : BaseEntityAudit
{
public override string Kod { get; set; }
public PolicyType PolicyType { get; set; } = PolicyType.Policy;
public long AgentId { get; set; }
public long InsuranceTypeId { get; set; }
public string PolicyNu { get; set; }
public long OwnerId { get; set; }
public string PlateNumber { get; set; }
public string Explanation { get; set; }
public Agent Agent { get; set; }
public InsuranceType InsuranceType { get; set; }
public Owner Owner { get; set; }
public virtual ICollection<SubPolicy> SubPolicies { get; set; }
}
public class SubPolicy : BaseEntityAudit
{
public override string Kod { get; set; }
public long PolicyId { get; set; }
public DateTime IssueDate { get; set; } = DateTime.Now.Date;
public DateTime StartDate { get; set; } = DateTime.Now.Date;
public DateTime EndDate { get; set; } = DateTime.Now.AddYears(1);
public decimal Premium { get; set; }
public long InsurerId { get; set; }
[StringLength(50)]
public Policy Policy { get; set; }
public Insurer Insurer { get; set; }
}
How can I insert related records of these tables to database under one side of one-to-many relationship, so under Policy entity?
Attention:I'm using EF Code-First model, not Db-First;
i am trying to display a list of cities with a country, a 1 to many relation.
I created the models for both of them:
City model
[Key]
public int ID_Cidade { get; set;
public int ID_Pais { get; set; }
public RH_Pais Pais { get; set; }
public string Nome { get; set; }
public Boolean Capital { get; set; }
public DateTime SysStartTime { get; set; }
public DateTime SysEndTime { get; set; }
public string Autor { get; set; }
public int OrdemCidade { get; set; }
public List<RH_Escritorios> Escritorios { get; set; }
Country model
[Key]
public int ID_Pais { get; set; }
public int ID_Moeda { get; set; }
public RH_Moeda Moeda { get; set; }
public string Nome { get; set; }
public string Nome_completo { get; set; }
public DateTime SysStartTime { get; set; }
public DateTime SysEndTime { get; set; }
public string Autor { get; set; }
public int OrdemPais { get; set; }
public List<RH_Cidades> Cidades { get; set; }
public List<RH_Idioma_Pais> Idiomas { get; set; }
and then i used fluent API to create the relationship
modelBuilder.Entity<RH_Cidades>()
.HasOne(m => m.Pais)
.WithMany(m => m.Cidades)
.HasForeignKey(m => m.ID_Pais);
and somehow when i generate the controller with EF, and i go to see the cities it causes a null error... this is because it has a include of the country when im trying to get the cities..
var rH_EntitiesContext = _context.RH_Cidades.Include(r => r.Pais).ToList();
The most annoying part is that i have the exact same situation in another relationship, with 1 to many and the include and it works perfectly!!
I have read and read my code for hours by now and i cannot see why the Include is giving me that error when in the offices controller with the same situation works...
Any help is appreciated!!!
I am a VB.NET programmer, but I am trying to learn C# and MVC in my spare time. I am using ASP.NET MVC 5.1.0.0 and I am trying to do code-First database creation in a local instance of SQL Server.
I was able to get the first database table to update in the database when I ran Update-Database from within the IDE, but when I added a second table that has a PK/FK relationship with the first, I am getting a red line under [ForeignKey] which reads
Does not contain a constructor that takes 1 arguments
I have been searching all over and not getting anywhere. Any suggestions or help would be appreciated. By the way, the first table is a PK/FK relationship to the AspNetUsers table.
public class BuildDatabase : IdentityUser
{
public virtual Companies Companies { get; set; }
public virtual NotaryProfile NotaryProfile { get; set; }
}
public class Companies
{
[Key]
[Column("CompanyID")] // Did this as the database will reflect TableName_ColumnName instead.
public int CompanyID { get; set; }
public string CompanyName { get; set; }
public bool IsActive { get; set; }
public bool IsNotary { get; set; }
public virtual ICollection<NotaryProfile> NotaryProfile { get; set; }
}
public class NotaryProfile
{
[Key]
public int NotaryID { get; set; }
public string NamePrefix { get; set; }
public string FirstName { get; set; }
public string MiddleInitial { get; set; }
public string LastName { get; set; }
public string NameSuffix { get; set; }
public bool IsActive { get; set; }
public int DefaultState { get; set; }
public int DefaultCounty { get; set; }
public bool IsSigningAgent { get; set; }
public bool HasABond { get; set; }
public decimal BondAmount { get; set; }
public bool HasEandO { get; set; }
public decimal EandOAmount { get; set; }
public bool ElectronicNotarizationsAllowed { get; set; }
public string ElectronicTechnologyUsed { get; set; }
public string ComissionNumber { get; set; }
public DateTime CommissionIssued { get; set; }
public DateTime CommssionOriginal { get; set; }
public DateTime CommissionExpires { get; set; }
public DateTime CommissionFiledOn { get; set; }
public string SOSAuditNumber { get; set; }
public string CommissionDesc { get; set; }
[Foreignkey("CompanyID")] // Companies.CompanyID = PK
public int CompanyID { get; set; } // PK/FK relationship.
public Companies Companies { get; set; } // Reference to Companies table above.
}
public class SchemaDBContext : IdentityDbContext<BuildDatabase>
{
public SchemaDBContext()
: base("DefaultConnection"){}
public DbSet<Companies> Companies { get; set; }
public DbSet<NotaryProfile> NotaryProfile { get; set; }
}
One of your classes (probably NotaryProfile) needs to reference another object (the foreign key relationship) but there is no constructor in that class that accepts an argument to establish that relationship, e.g.:
public NotaryProfile(int companyId) {
this.companyId = companyId;
}
BTW, a better way to establish that relationship is to use the actual class type rather than the ID, as in:
public class NotaryProfile {
...
public Company Company { get; set; }
// Instead of this:
// public int CompanyID { get; set; } // PK/FK relationship.
...
}
See also:
C# “does not contain a constructor that takes '1' arguments”
Does not contain a constructor that takes 2 arguments
I want to map from
LDTTicketUploadDTO[] to IEnumerable<LDTTicket>
The mappings are created in this method and at the end I map the data.
public void UploadLDTTickets(LDTTicketUploadDTO[] ticketDTOs)
{
Mapper.CreateMap<LDTTicketUploadDTO, LDTTicket>();
Mapper.CreateMap<LDTTicketDTO, LDTTicket>();
Mapper.CreateMap<LDTCustomerDTO, LDTCustomer>();
Mapper.CreateMap<LDTDeviceDTO, LDTDevice>();
Mapper.CreateMap<LDTUnitDTO, LDTUnit>();
Mapper.CreateMap<LDTCommandDTO, LDTCommand>();
Mapper.CreateMap<LDTCommandParameterDTO, LDTCommandParameter>();
Mapper.CreateMap<LDTObjectDTO, LDTObject>();
Mapper.CreateMap<LDTControlFileDTO, LDTControlFile>();
Mapper.CreateMap<LDTDeviceDTO, LDTDevice>();
Mapper.CreateMap<LDTLanguageDTO, LDTLanguage>();
Mapper.CreateMap<LDTObjectBitDTO, LDTObjectBit>();
var tickets = Mapper.Map<IEnumerable<LDTTicketUploadDTO>, IEnumerable<LDTTicket>>(ticketDTOs);
// do something with tickets
}
This is how the DTO´s are structured:
public class LDTTicketUploadDTO
{
public LDTTicketDTO Ticket { get; set; }
public LDTDeviceDTO Device { get; set; }
public LDTCustomerDTO Customer { get; set; }
}
public enum TicketStatus
{
New,
InProgress,
Done
}
public class LDTTicketDTO
{
public bool UploadNeeded { get; set; }
public string TicketNumber { get; set; }
public TicketStatus Status { get; set; }
public string CreatedBy { get; set; }
public DateTime CreatedOn { get; set; }
public string AssignedTo { get; set; }
public IEnumerable<LDTUnitDTO> Units { get; set; }
}
public class LDTUnitDTO
{
public int Id { get; set; }
public string FunctionUnit { get; set; }
public int FunctionUnitAddress { get; set; }
public string Zone { get; set; }
public int ZoneUnitAddress { get; set; }
public string Object { get; set; }
public int ObjectAddress { get; set; }
public IEnumerable<LDTCommandDTO> Commands { get; set; }
}
and more...
What works is that these properties are correctly mapped to their counterpart entities:
public LDTDeviceDTO Device { get; set; }
public LDTCustomerDTO Customer { get; set; }
What works NOT is that this property is not mapped:
public LDTTicketDTO Ticket { get; set; }
This is how the Entities are structured:
public class LDTTicket
{
[Key, Column(Order = 0)]
[Required]
public string SerialNumber { get; set; }
[Key, Column(Order = 1)]
[Required]
public string TicketNumber { get; set; }
[Required]
public DateTime CreatedOn { get; set; }
[Required]
public string AssignedTo { get; set; }
public TicketStatus Status { get; set; }
public string CreatedBy { get; set; }
public bool UploadNeeded { get; set; }
public virtual LDTCustomer Customer { get; set; }
public virtual LDTDevice Device { get; set; }
public virtual ICollection<LDTUnit> Units { get; set; }
}
ONLY the Customer and Device property are mapped in the LDTTicket
What is wrong with my configuration?
It's expecting to populate a LDTTicket sub-property on the ticket, not the matching properties of the ticket itself. Create direct mappings onto the ticket from the Ticket subproperty of the source directly onto the matching properties of the destination. NOTE: You only need to define your mappings once, not per method execution. Mappings should be defined at app start up and thereafter used.
public void UploadLDTTickets(LDTTicketUploadDTO[] ticketDTOs)
{
Mapper.CreateMap<LDTTicketUploadDTO, LDTTicket>();
.ForMember(d => d.SerialNumber, m => m.MapFrom(s => s.Ticket.SerialNumber))
...
//Mapper.CreateMap<LDTTicketDTO, LDTTicket>(); You don't need this
Mapper.CreateMap<LDTCustomerDTO, LDTCustomer>();
Mapper.CreateMap<LDTDeviceDTO, LDTDevice>();
...
}
I need to generate a primary key by mask (for example: BS{100-999}-{Rand(100-999)}) But I do not know how to generate a key like this in EF code/ Could somebody help me please to figure this out?
My model:
[Table("Tickets")]
public class Ticket
{
public Ticket()
{
CreationDate = DateTime.UtcNow;
LastChangeDate = DateTime.UtcNow;
UserReviewed = true;
EmailAlert = true;
}
[Key]
[DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; } //now it is Guid But i need this to be string and generated by the above mask
public string UsersName { get; set; }
public string Theme { get; set; }
public string Request { get; set; }
public DateTime CreationDate { get; set; }
public string TypeMask { get; set; }
public string StatusMask { get; set; }
public int SenderId { get; set; }
public bool EmailAlert { get; set; }
public DateTime LastChangeDate { get; set; }
public bool UserReviewed { get; set; }
public virtual ICollection<TicketRecord> Answers { get; set; }
[ForeignKey("StatusMask")]
public virtual TicketStatus Status { get; set; }
[ForeignKey("TypeMask")]
public virtual TicketType Type { get; set; }
[ForeignKey("SenderId")]
public virtual UserProfile Sender { get; set; }
public virtual AttachmentsCollection IncludedFiles { get; set; }
}
EF never generates keys. Either you need to generate the key by yourself or you let the EF know that the key will be generated by the database using StoreGeneragedPattern annotation/setting. EF cannot generate keys as it cannot guarantee uniquenesses for the generated values.