I have a database issue. well im not sure exactly what to do. Im using the codefirst approach in an mvc5 project.
Currently my primary keys for my tables are auto generated and they increase. eg. customerid - 0,1,2,3 etc.
I want to know, how do i add a prefix to this id, eg i want it to be Cust0 instead of just 0.
The question is what is the reason you want to have this kind of "key"? You can auto generate ID for your customer and create your own property:
public class Customer
{
public const string CustomerPrefix = "Cust";
[Key]
public int Id {get; set;}
[NotMapped]
public string CustomerId
{
get { return string.Concat(CustomerPrefix, Id)}
}
}
Btw.: It is really bad practice to have PK as a string (because of performance)
Related
When a run a GET request i get an exception o.h.engine.jdbc.spi.SqlExceptionHelper : Unknown column 'disburseme0_.reason_type' in 'field list' in stack trace even though i have configured the field correctly in the entity class. I have a Spring Boot SOAP interface that is querying a MySql database view. I have assigned one of the unique keys from the parent tables as the view Id in JPA.
Part of my entity class has:
#Entity
#Table(name="disbursement_payload")
public class Disbursement {
#Id
#Column(name="ID")
private long disbursementId;
#Column(name="ReasonType")
private String reasonType;
public long getDisbursementId() {
return disbursementId;
}
public void setDisbursementId(long disbursementId) {
this.disbursementId = disbursementId;
public String getReasonType() {
return reasonType;
}
public void setReasonType(String reasonType) {
this.reasonType = reasonType;
}
I have the view as:
CREATE VIEW disbursement_payload AS (
SELECT
iso_number AS Currency,
trans_desc AS ReasonType,
account_number AS ReceiverParty,
amount AS Amount
FROM m_payment_detail, m_loan_transaction
WHERE m_payment_detail.`id`= m_loan_transaction.`payment_detail_id` AND
m_payment_detail.`payment_type_id`=2
);
Is there something im missing , in the entity or view definition? I have read one of the comments here could not extract ResultSet in hibernate that i might have to explicitly define the parent schemas. Any assistance, greatly appreciated.
do the mapping for db column and class var name based on camelCase conversion basded on underscore _ separated name
you could try using
CREATE VIEW disbursement_payload AS (
SELECT iso_number AS currency
, trans_desc AS reason_type
, account_number AS receiver_rarty
, amount AS amount
FROM m_payment_detail
INNER JOIN m_loan_transaction
ON m_payment_detail.`id`= m_loan_transaction.`payment_detail_id`
AND m_payment_detail.`payment_type_id`=2
);
the view code is SQL code and hibernate see a view as a table, so the conversion of column name is base on the same rules
and a suggestion you should not use (older) implicit join based on where condition you should use (more recent) explici join sintax ..
I'm developing a J2EE 6 Web Application, using a MySql 5.02 DataBase. I'm trying to generate a hash digest of the ID, every time I create a new Entity. This is set to a column on the Table.
But well, I'm stuck on something that is apparently easy, and according with what I found googling, possible. Basically I want to retrieve the ID (Primary Key) of a newly persisted object, but whatever I try, it returns null.
The steps are follow are:
Create the Instance of the Entity -> userCard = new Users();
Setting the corresponding fields with some values.
Calling the persist() method of the EntityManager.
After reading some forums, I understood I had to either call flush() after persist(), or use merge() and use the returned entity to retrieve the id.
public void createAndFlush(Users users) {
em.persist(users);
em.flush();
}
public Integer edit(Users users) {
return ((Users)em.merge(users)).getIdvcards();
}
None of them (among some other combinations) work, well, the Entity is successfully persisted, but the ID field returns null.
These are the correspinding annotations of the id column I want to retrieve:
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "idvcards")
private Integer idvcards;
And obviously, the column idvcards of my table is set to Auto-Increment and Primary Key.
Maybe I just need to clarify my Peristence-Management concepts, but I'd appreciate if I can get some hint to solve this basic issue.
Maybe is not the most elegant solution ever, but finally I succeded on retrieving the ID of the new Entity:
public Integer create(User user) {
em.persist(users);
em.flush();
return (Integer) em.getEntityManagerFactory().getPersistenceUnitUtil().getIdentifier(users);
}
And well, althought is not related to the functionality, I changed the entity name to the singular form as #Bohemian suggested.
Try this, it works for me:
#Id
#GeneratedValue
#Column(name = "id", unique = true, nullable = false)
Also, I don't use the value returned from merge. I just persist then flush and the entity object magically gets the new key value.
p.s. Tables should never be named in the plural, and especially not the entity class. Call the class User (and the table if you can). Otherwise it's just confusing: Users sounds like a collection of User.
It will work fine
em.persist(usmApproveTransaction);
em.flush();
System.out.println("++++++e++++++++"+usmApproveTransaction.getUatApproveTransIdPk());
return usmApproveTransaction;
I'm getting id using em.flush(); after persist
++++++e++++++++51472
I'm trying to do a basic lnq to sql foreign key mapping using attributes. This should be really simple but I'm having a hard time finding decent info on it on the net. Where am I going wrong?
Say for example you have a class named User with UserId, FirstName, LastName, Location on it. Location is an object called Location
Location class has LocationId, StreetNum, Name, Suburb
How do I map that with Linq to Sql?
Here's what I'm trying
[Column]
public int LocationId { get; set; }
private EntityRef<Location> _location;
[Required(ErrorMessage = "Please enter your suburb")]
[System.Data.Linq.Mapping.Association(Storage = "_location", ThisKey = "LocationId", IsForeignKey = true)]
public Location Location
{
get { return this._location.Entity; }
set { this._location.Entity = value;
LocationId = value.LocationId;
}
}
I'm getting this error:
The null value cannot be assigned to a member with type System.Double which is a non-nullable value type.
Can anyone help?
Probably, somewhere you've used double datatype (StreetNum, maybe).
In the database corresponding column is marked with NULL flag. Try to use double? or Nullable<double> datatype for your properties.
Using Linq to SQL and the autogeneration capabilities of DBML, foreign key relationships create EntityRefs in the DBML designer file. For example :
private int _USStateId;
private EntityRef<USState> _USState;
However, if I have the need for a table with numerous FK relationships to the same table, how can i control the autogenerated names? For example, for a Car survey with three FKs into a Ratings table, I get
private int _BodyRatingId;
private int _ColorRatingId;
private int _PerformanceRatingId;
in my Car table with
private EntityRef<Rating> _Rating;
private EntityRef<Rating> _Rating1;
private EntityRef<Rating> _Rating2;
How can I, dynamically or other wise, control the EntityRef naming to indicate that they pertain to a particular field?
Thanks!
Hi
I'm not sure if the question is still valid but in case anybody needs it:
You can add a partial class to your project with the same name as your Car table and add new properties:
public Rating BodyRating
{
get
{
return this._Rating.Entity;
}
}
How do I code the Select clause in my LINQ satament to select column aliases so I can sort on them basically I want to accomplish this SQL statement in LINQ:
select
type_id as id,
type_desc as description
from
dbo.equip_type_avt
order by
description
What do I replace the ????? in my .Select clause in my LINQ statement?
public IQueryable<equip_type_avt> GetGridEquipmentTypes(string sidx, string sord)
{
try
{
return
ulsDB.equip_type_avts
.Select(?????)
.OrderBy(sidx + " " + sord);
}
catch (Exception ex)
{
string strErr = ex.Message;
return null;
}
}
You can use an anonymous type:
table.Select(x => new
{
ID = x.type_id,
Description = x.type_desc
});
However, you can't access the properties of an anonymous type outside of the scope where it is declared (without reflection or other dirty hackery, anyway) so if you want to use the result outside of that function you just create a class and create an instance of it in the query using a type initializer:
public class Foobar
{
public int ID { get; set; }
public string Description { get; set; }
}
...
table.Select(x => new Foobar() // Note the difference here
{
ID = x.type_id,
Description = x.type_desc
});
Question though: if you want to name the columns differently, why don't you change it in the place where the column-property mapping is declared? In LINQ-to-SQL you can have the database column be named whatever you like but give the property the name "ID" or "Description".
I'm not sure i understand your question, how does sidx and sord relate to your query?
Isn't your problem rather that you have to end your query with OrderBy(...).ThenBy(...) instead of a combined OrderBy?
If you want to sort by a string in the easy way, download the Dynamic LINQ library.
However, that's 2000 lines of code, most of which are entirely redundant for just the purpose of sorting.
Doing it yourself shouldn't be too hard, but requires a fair bit of knowledge on expression trees. I can't really help you there though.
EDIT: I've added another answer, that hopefully answers your actual question :)