ORMLite Save does not update model with the autoincrement identity - c#

I'm using servicestack, ormlite, and mysql and Have linked table that are created within a transaction. Using the connection Save method, it should (according to documentation) update the model with the identity value. But it does not.
public bool SaveWithCredentials<T>(T model)
{
SetDefaultValues(false, model);
var ret = Db.Save(model);
return ret;
}
(EDITED WITH MODEL)
The model:
[Alias("orderEvent")]
public class OrderEvent
{
[AutoIncrement]
[Alias("Identity")]
public long Identity { get; set; }
[Required]
[StringLength(DbConstraints.STRING_36, DbConstraints.STRING_36)]
[Alias("Id")]
public string Id { get; set; }
[Required]
[StringLength(DbConstraints.STRING_36, DbConstraints.STRING_36)]
[Alias("orderId")]
public string OrderId { get; set; }
[Required]
[Alias("meaning")]
public int Meaning { get; set; }
[Required]
[Alias("subMeaning")]
public int SubMeaning { get; set; }
[Alias("quantity")]
public int Quantity { get; set; }
[Required]
[Alias("type")]
public int Type { get; set; }
[StringLength(DbConstraints.STRING_36, DbConstraints.STRING_36)]
[Alias("servicesaleId")]
public string ServiceSaleId { get; set; }
[Required]
[StringLength(DbConstraints.STRING_36, DbConstraints.STRING_36)]
[Alias("servicecenterId")]
public string ServiceCenterId { get; set; }
[StringLength(DbConstraints.STRING_36, DbConstraints.STRING_36)]
[Alias("projectId")]
public string ProjectId { get; set; }
[Alias("ecoDate")]
public DateTime EcoDate { get; set; }
[Alias("createdDate")]
public DateTime CreatedDate { get; set; }
[StringLength(DbConstraints.STRING_50)]
[Alias("createdByName")]
public string CreatedByName { get; set; }
[StringLength(DbConstraints.STRING_36, DbConstraints.STRING_36)]
[Alias("createdbyuserId")]
public string CreatedByUserId { get; set; }
[StringLength(DbConstraints.STRING_2000)]
[Alias("generalDescription")]
public string GeneralDescription { get; set; }
[Required]
[StringLength(DbConstraints.STRING_50)]
[Alias("sysecoactionId")]
public string SysEcoActionId { get; set; }
[StringLength(50)]
[Alias("sysOrderSerie")]
public string SysOrderSerie { get; set; }
[Alias("orderNbr")]
public int? OrderNbr { get; set; }
[Alias("itemNbr")]
public int? ItemNbr { get; set; }
}
The IDBConnection.Save should update the field with the autoincrement identity in the model so that I can set the foreign key in the linked table, but it does not.
Does anyone have any idea? I cannot do the insert method, since it would have me doing major rewrite - which sort of negates the purpose of the Save method!
UPDATE
Tried the model in a test method with insert method and I get the identity returned then.
public long InsertForIdWithCredentials<T>(T model)
{
SetDefaultValues(false, model);
var ret = Db.Insert(model, selectIdentity: true);
return ret;
}
the above code have no problem with returning identity even if it is generic.
/Erik

Related

How to to make properties visible when the Foreign Key comes up as ICollection<T> type in Entity Framework's .edmx's .tt classes [.NET]

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 in referenced table 'x' that match referencing column foreign key ".y"

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.

Entity Framework - Update action and Automapper

For example, I have the following infrastructure class:
[Table("GeoHistory")]
public partial class GeoHistory
{
public int Id { get; set; }
public int CompanyId { get; set; }
public int DriverId { get; set; }
[StringLength(50)]
public string Name { get; set; }
public string Description { get; set; }
[StringLength(100)]
public string GeofenceLocation { get; set; }
[StringLength(100)]
public string GeofencePrevious { get; set; }
[StringLength(20)]
public string StateLocation { get; set; }
[StringLength(20)]
public string StatePrevious { get; set; }
public DateTime? DateTime { get; set; }
[StringLength(5)]
public string Heading { get; set; }
public decimal? Speed { get; set; }
[StringLength(50)]
public string Status { get; set; }
}
and the following View class (let's forget about domain layer):
public class GeoHistoryViewModel
{
public int Id { get; set; }
public int? CompanyId { get; set; }
public int? DriverId { get; set; }
[StringLength(50)]
public string Name { get; set; }
public string Description { get; set; }
}
as we can see, we edit only part of field list.
Now, we want to update data in DB. Of course, we can write like:
Infrastructure.Main.GeoHistory geoHistory = db.GeoHistories.Find(id);
geoHistory.CompanyId = model.CompanyId;
geoHistory.DriverId = model.DriverId;
geoHistory.Name = model.Name;
........
db.SaveChanges();
It works. But I want to use Automapper. And if I try to do the following:
Infrastructure.Main.GeoHistory geoHistory = mapper.Map<Infrastructure.Main.GeoHistory>(model);
db.GeoHistories.Attach(geoHistory);
db.Entry(geoHistory).State = EntityState.Modified;
db.SaveChanges();
It works, but of course remove values of fields, which are not exist in View Model, but exist in infrastructure class. How to use automapper, but don't lost these fields?

Code-First SQL Server ASP.NET MVC6

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

Entity Framework How to generate PrimaryKey by mask

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.

Categories