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.
Related
I have 2 Tables in the SQL Server SUST_HC_DTLS [Primary Key Column Name = SUST_ID] and the second table is SUST_INC_TRCKR_DTLS [Foreign Key = SUST_HANDLER (it references SUST_ID column of first table. This Table also has a Primary Key column = INC_NBR)].Now when i create the Entity Data Model. It create 2 partial classes for both the Table. As show Below --
For Table = SUST_HC_DTLS (Primary Key Table)
public partial class SUST_HC_DTLS
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public SUST_HC_DTLS()
{
this.SUST_INC_TRCKR_DTLS = new HashSet<SUST_INC_TRCKR_DTLS>();
}
public int SUST_ID { get; set; }
public string HC_NAME { get; set; }
public string HC_EMAIL { get; set; }
public Nullable<System.TimeSpan> SHIFT_START { get; set; }
public Nullable<System.TimeSpan> SHIFT_END { get; set; }
public Nullable<System.DateTime> JOINED_ON { get; set; }
public Nullable<System.DateTime> UPDTD_AT { get; set; }
public string UPDTD_BY { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<SUST_INC_TRCKR_DTLS> SUST_INC_TRCKR_DTLS { get; set; }
}
For Secondary Table = SUST_INC_TRCKR_DTLS (Foreign Key Table)
public partial class SUST_INC_TRCKR_DTLS
{
public string INC_NBR { get; set; }
public string REASON_4_INC { get; set; }
public string RAISED_BY { get; set; }
public int SUST_HANDLER { get; set; }
public string COMMENTS { get; set; }
public string CURRENT_STTS { get; set; }
public Nullable<System.DateTime> CREATED_ON { get; set; }
public string DTLS_ENTRD_BY { get; set; }
public Nullable<System.DateTime> UPDTD_ON { get; set; }
public string DTLS_UPDTD_BY { get; set; }
public virtual SUST_HC_DTLS SUST_HC_DTLS { get; set; }
}
Now, I have separate Class Library for My Models for these respective Table and Below are the Classes in the Class Library --
For Primary Table --
public class HC_TBL
{
[Required]
public int SUST_ID { get; set; }
[Required]
public string HC_NAME { get; set; }
[EmailAddress]
public string HC_EMAIL { get; set; }
[Required]
[DataType(DataType.Time)]
public TimeSpan? SHIFT_START { get; set; }
[Required]
[DataType(DataType.Time)]
public TimeSpan? SHIFT_END { get; set; }
[Required]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime? JOINED_ON { get; set; }
public DateTime? UPDTD_AT { get; set; }
public string UPDTD_BY { get; set; }
public INC_Trckr_TBL Trckr_TBL { get; set; }
}
For Foreign Key Table
public class INC_Trckr_TBL
{
public string INC_NBR { get; set; }
//[Required]
public string REASON_4_INC { get; set; }
//[Required]
public string RAISED_BY { get; set; }
public int SUST_HANDLER { get; set; }
public string COMMENTS { get; set; }
//[Required]
public string CURRENT_STTS { get; set; }
public DateTime? CREATED_ON { get; set; }
public string DTLS_ENTRD_BY { get; set; }
public DateTime? UPDTD_ON { get; set; }
public string DTLS_UPDTD_BY { get; set; }
}
Now when i do the Database Operations to get all records from the Database. Its not letting me call Foreign key properties /fields. It doesn't even provide them in the list.
However, when i do the LINQ Select from the options i get, i do get the property but then it gives me the error -- Cannot implicitly convert type System.Collections.Generic.IEnumerable to GDE.Model.INC_Trckr_TBL. An explicit conversion exists (Are you missing one?).
Now when i do the explicit conversion it says --
System.NotSupportedException
HResult=0x80131515
Message=Values of type 'collection[Edm.String(Nullable=True,DefaultValue=,MaxLength=20,Unicode=False,FixedLength=False)]' can not be converted to string.
I Honestly don't know what to do anymore. Below is my DBOperations Repository Code --
public List<SustHCModel> GetAllDetails()
{
using (var context = new GDE_SUSTEntities())
{
var result= context.SUST_HC_DTLS.Select(x => new SustHCModel()
{
SUST_ID = x.SUST_ID,
HC_NAME = x.HC_NAME,
HC_EMAIL = x.HC_EMAIL,
SHIFT_START = x.SHIFT_START,
SHIFT_END = x.SHIFT_END,
JOINED_ON = x.JOINED_ON,
IncTrckrModel = new INCTrckrModel()
{
INC_NBR = x.SUST_INC_TRCKR_DTLS.Select(y => y.INC_NBR).ToString(),
REASON_4_INC = x.SUST_INC_TRCKR_DTLS.Select(y => y.REASON_4_INC).ToString(),
RAISED_BY = x.SUST_INC_TRCKR_DTLS.Select(y => y.RAISED_BY).ToString(),
COMMENTS = x.SUST_INC_TRCKR_DTLS.Select(y => y.COMMENTS).ToString(),
CURRENT_STTS = x.SUST_INC_TRCKR_DTLS.Select(y => y.CURRENT_STTS).ToString()
}
}).ToList();
return result;
}
}
I am new to this. So, i am pretty sure that i have made some mistake somewhere. So, please guide me and my apologies in advance for whatever silly mistake i have made.
There are no primary or candidate keys in the referenced table 'dbo.Client_Master' that match the referencing column list in the foreign key 'FK_dbo.Client_Question_Master_dbo.Client_Master_client_id'.
Could not create constraint or index. See previous errors.
My Client_Master Model
public class Client_Master
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long Client_Id { get; set; }
public string Client_Name { get; set; }
public string Client_Address { get; set; }
public string Client_Email { get; set; }
public string Client_Phone { get; set; }
[DefaultValue(" ")]
public string Client_Country { get; set; }
[DefaultValue(" ")]
public string Client_State { get; set; }
[DefaultValue(" ")]
public string Client_Postcode { get; set; }
public bool Is_Active { get; set; }
public long? Created_By { get; set; }
public DateTime? Created_Date { get; set; }
[ForeignKey("Business_Master")]
public long? Business_Id { get; set; }
[ForeignKey("Categories")]
public long? Category_Id { get; set; }
public virtual Categories Categories { get; set; }
public virtual Business_Master Business_Master { get; set; }
[JsonIgnore]
public virtual ICollection<Client_Question_Master> Client_Question_Master { get; set; }
}
And My Client_Question_Master Modal
public class Client_Question_Master
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long client_question_master_id { get; set; }
[ForeignKey("Client_Master")]
public long? client_id { get; set; }
public virtual Client_Master Client_Master { get; set; }
[ForeignKey("Question_Types")]
public long? question_type_id { get; set; }
public virtual Question_Types Question_Types { get; set; }
public string question { get; set; }
public long order_no { get; set; }
public bool isContribute { get; set; } = true;
[ForeignKey("Section_Master")]
public long? section_id { get; set; }
public virtual Section_Master Section_Master { get; set; }
public double amount { get; set; }
public bool isActive { get; set; } = true;
public bool isRequired { get; set; } = true;
public bool isComment { get; set; } = true;
public string values { get; set; }
public bool isRevenue { get; set; }
public bool isStaff { get; set; }
public bool isMarketing { get; set; }
public DateTime created_date { get; set; } = DateTime.Now;
}
After add-migration during updating database it is giving me error.
Your usage of the ForeignKey attribute is the wrong way round, when using a nullable foreign key.
For example you use:
[ForeignKey("Client_Master")]
public long? client_id { get; set; }
public virtual Client_Master Client_Master { get; set; }
However it should be:
public long? client_id { get; set; }
[ForeignKey("client_id")]
public virtual Client_Master Client_Master { get; set; }
You tell EntityFramework what property is the foreign key. This prevent it from creating a field that has the same datatype as the primary key.
Check your edmx file.Edmx may not have that column as Primary key in another table which you are using as foreign key.
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 am been using entity framework for my application. Unfortunately I can't make expressions like this one in entity framework:
List<MyUser> users = (from user in database.MyUsers
join app in database.MyApplications
on user.ApplicationId equals app.Id
where app.Name == this._applicationName
&& user.MyRoles.Contains(existingRole)
select user).ToList();
Any other approaches to this one. I don't want to change my database or my models. In my case the relationship between MyUser and MyRole is many to many with a glue table.
This is how the MyUser class is declared:
public partial class MyUser
{
public MyUser()
{
this.MyApiTokens = new HashSet<MyApiToken>();
this.MyLandingPages = new HashSet<MyLandingPage>();
this.MyPresentations = new HashSet<MyPresentation>();
this.MySlides = new HashSet<MySlide>();
this.MyUserSettings = new HashSet<MyUserSetting>();
this.MyRoles = new HashSet<MyRole>();
}
public System.Guid Id { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string EmailAddress { get; set; }
public int ApplicationId { get; set; }
public System.DateTime CreateDate { get; set; }
public System.DateTime LastActivityDate { get; set; }
public System.DateTime LastLockoutDate { get; set; }
public System.DateTime LastLoginDate { get; set; }
public System.DateTime LastPasswordChangedDate { get; set; }
public string PasswordQuestion { get; set; }
public string PasswordAnswer { get; set; }
public string Comment { get; set; }
public bool IsLocked { get; set; }
public bool IsApproved { get; set; }
public virtual ICollection<MyApiToken> MyApiTokens { get; set; }
public virtual MyApplication MyApplication { get; set; }
public virtual ICollection<MyLandingPage> MyLandingPages { get; set; }
public virtual ICollection<MyPresentation> MyPresentations { get; set; }
public virtual ICollection<MySlide> MySlides { get; set; }
public virtual ICollection<MyUserSetting> MyUserSettings { get; set; }
public virtual ICollection<MyRole> MyRoles { get; set; }
}
Assuming MyRoles is an association property in the entity model (i.e. maps to a table), you may want to make the matching explicit on the primary key of the role object. For example:
user.MyRoles.Any(r => r.RoleId == existingRole.RoleId)
There isn't enough information in your question to give an exact answer, though.