how to retrieve last entry primarykey? [duplicate] - c#-4.0

This question already has answers here:
How to get the identity of an inserted row?
(15 answers)
Closed 8 years ago.
public int retrieveID()
{
int lastEntry = 0;
try
{
queryString = "Select ID from Database";
myComm = new OleDbCommand(queryString, myConn);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return lastEntry;
}
I want to retrieve the last primary key used in access database, whereas i set my primary key as autonumber.
elaborating more..
I am working on a database application and want to utilize the primary key, eg if the last entry in the database was 10, i want to retrieve 10, i tried simple query but that didnot work.

If you are using an OLEDB connection then this should work
queryString = "SELECT ##IDENTITY";
Note that this should be called immediately after the INSERT that creates the record for which you want to save the ID value. If your code were to create other records with Identity (AutoNumber) fields then the ##IDENTITY value will be updated (replaced) by those calls.

Related

Table Keeps Appearing Empty When I Start App MVC 5 Identity

Good Evening,
I used this tutorial https://learn.microsoft.com/en-us/aspnet/identity/overview/getting-started/aspnet-identity-using-mysql-storage-with-an-entityframework-mysql-provider
and if I create a user, then close the app, restart it then try to login again, I get username invalid. I have traced the issue to the following code. Specifically the last method below. That method fires every time I register a new user and login. It deletes the table and recreates it. If I take the it out, then when it doesn't create the database if it's empty. It just throws an exception saying the table is not found. How can I fix this to work correctly?
Thanks,
Steven
public class MySqlInitializer : IDatabaseInitializer<ApplicationDbContext>
{
public void InitializeDatabase(ApplicationDbContext context)
{
if (!context.Database.Exists())
{
// if database did not exist before - create it
context.Database.Create();
}
else
{
// query to check if MigrationHistory table is present in the database
var migrationHistoryTableExists = ((IObjectContextAdapter)context).ObjectContext.ExecuteStoreQuery<int>(
"SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'IdentityMySQLDatabase' AND table_name = '__MigrationHistory'");
// if MigrationHistory table is not there (which is the case first time we run) - create it
if (migrationHistoryTableExists.FirstOrDefault() == 0)
{
context.Database.Delete();
context.Database.Create();
}
}
}
}

ServiceStack: Update<T>(...) produces 'duplicate entry'

I have tried reading the docs, but I don't get why the Update method produces a "Duplicate entry" MySQL error.
The docs says
In its most simple form, updating any model without any filters will update every field, except the Id which is used to filter the update to this specific record:
So I try it, and pass in an object, like below. A row with id 2 already exists.
using (var _db = _dbFactory.Open())
{
Customer coreObject = new Customer(...);
coreObject.Id = 2;
coreObject.ObjectName = "a changed value";
_db.Update<Customer>(coreObject); // <-- error "duplicate entry"
}
Yes, there are options using .Save and such, but what am I missing with the .Update? As I read it, it should use its Id property to update the row in the db, not insert a new row?
The issue with this method is that you're updating a generic object T but your Update API says to update the Concrete Customer type:
public void MyTestMethod<T>(T coreObject) where T : CoreObject
{
long id = 0;
using (var _db = _dbFactory.Open())
{
id = _db.Insert<T>(coreObject, selectIdentity: true);
if (DateTime.Now.Ticks == 0)
{
coreObject.Id = (uint)id;
_db.Delete(coreObject);
}
if (DateTime.Now.Ticks == 0)
{
_db.DeleteById<Customer>(id);
}
if (DateTime.Now.Ticks == 0)
{
coreObject.Id = (uint)id;
coreObject.ObjectName = "a changed value";
_db.Update<Customer>(coreObject);
}
}
}
Which OrmLite assumes that you're using a different/anonymous object to update the customer table, similar to:
db.Update<Customer>(new { Id = id, ObjectName = "a changed value", ... });
Which as it doesn't have a WHERE filter will attempt to update all rows with the same primary key.
What you instead want is to update the same entity, either passing in the Generic Type T or have it inferred by not passing in any type, e.g:
_db.Update<T>(coreObject);
_db.Update(coreObject);
Which will use OrmLite's behavior of updating entity by updating each field except for Primary Keys which it instead used in the WHERE expression to limit the update to only update that entity.
New Behavior in v5.1.1
To prevent accidental misuse like this I've added an Update API overload in this commit which will use the Primary Key as a filter when using an anonymous object to update an entity, so your previous usage:
_db.Update<Customer>(coreObject);
Will add the Primary Key to the WHERE filter instead of including it in the SET list. This change is available from v5.1.1 that's now available on MyGet.

java.lang.NullPointerException when using returning().fetchOne()

Note: This code used to work as I used PostgreSQL. After switching to MySQL these functions stopped working for some reason.
I double checked: languageId and shopId are valid IDs and there is a valid entry of supported_language resembling the inserted record after fetchOne() but it returns null.
private Long addSupportedLanguage(Long languageId, Long shopId) {
Long value = this.ctx.insertInto(SHOP_LANGUAGE)
.set(SHOP_LANGUAGE.LANGUAGE_ID, languageId)
.set(SHOP_LANGUAGE.SHOP_ID, shopId)
.returning()
.fetchOne() // After this line I see the record in my db but it returns null
.getValue(SHOP_LANGUAGE.LANGUAGE_ID);
return value;
}
I also tried using
.returning(RESTAURANT_LANGUAGE.LANGUAGE_ID)
but the result is the same.
I am observing something similar when calling returnin() after a delete() statement:
public void deleteEmailVerificationToken(String token) {
ShopAdminVerificationTokenRecord shopAdminVerificationTokenRecord = this
.ctx.delete(SHOP_ADMIN_VERIFICATION_TOKEN)
.where(SHOP_ADMIN_VERIFICATION_TOKEN.VERIFICATION_TOKEN.eq(token))
.returning()
.fetchOne()
.into(SHOP_ADMIN_VERIFICATION_TOKEN);
if(shopAdminVerificationTokenRecord != null) {
LOGGER.debug("Deleted verification token for " + shopAdminVerificationTokenRecord.getUserEmail());
} else {
LOGGER.debug("The given token was not found.");
}
}
I don't understand why this is happening. The new record gets correctly inserted but still I cannot fetch that record immediately after insertion.
I created SHOP_LANGUAGE and all other objects using the jOOQ code generator. This is the SQL CREATE TABLE statement that I used to create the table for a MySQL database:
CREATE TABLE shop_language (
shop_id BIGINT NOT NULL,
CONSTRAINT fk__shop_language__shop
FOREIGN KEY (shop_id)
REFERENCES shop(id),
language_id BIGINT NOT NULL,
CONSTRAINT fk__shop_language__language
FOREIGN KEY (language_id)
REFERENCES language(id),
PRIMARY KEY (shop_id, language_id)
);
As mentioned in the comments:
DELETE .. RETURNING is not supported for MySQL as documented by the #Support annotation on the relevant returning() methods.

Linq queries and optionSet labels, missing formatted value

I'm doin a simple query linq to retrieve a label from an optionSet. Looks like the formatted value for the option set is missing. Someone knows why is not getting generated?
Best Regards
Sorry for the unclear post. I discovered the problem, and the reason of the missing key as formattedvalue.
The issue is with the way you retrieve the property. With this query:
var invoiceDetails = from d in xrmService.InvoiceSet
where d.InvoiceId.Value.Equals(invId)
select new
{
name = d.Name,
paymenttermscode = d.PaymentTermsCode
}
I was retrieving the correct int value for the option set, but what i needed was only the text. I changed the query this way:
var invoiceDetails = from d in xrmService.InvoiceSet
where d.InvoiceId.Value.Equals(invId)
select new
{
name = d.Name,
paymenttermscode = d.FormattedValues["paymenttermscode"]
}
In this case I had an error stating that the key was not present. After many attempts, i tried to pass both the key value and the option set text, and that attempt worked just fine.
var invoiceDetails = from d in xrmService.InvoiceSet
where d.InvoiceId.Value.Equals(invId)
select new
{
name = d.Name,
paymenttermscode = d.PaymentTermsCode,
paymenttermscodeValue = d.FormattedValues["paymenttermscode"]
}
My guess is that to retrieve the correct text associated to that option set, in that specific entity, you need to retrieve the int value too.
I hope this will be helpful.
Best Regards
You're question is rather confusing for a couple reasons. I'm going to assume that what you mean when you say you're trying to "retrieve a label from an OptionSet" is that you're attempting to get the Text Value of a particular OptionSetValue and you're not querying the OptionSetMetadata directly to retrieve the actual LocalizedLabels text value. I'm also assuming "formatted value for the option set is missing" is referring to the FormattedValues collection. If these assumptions are correct, I refer you to this: CRM 2011 - Retrieving FormattedValues from joined entity
The option set metadata has to be queried.
Here is an extension method that I wrote:
public static class OrganizationServiceHelper
{
public static string GetOptionSetLabel(this IOrganizationService service, string optionSetName, int optionSetValue)
{
RetrieveOptionSetRequest retrieve = new RetrieveOptionSetRequest
{
Name = optionSetName
};
try
{
RetrieveOptionSetResponse response = (RetrieveOptionSetResponse)service.Execute(retrieve);
OptionSetMetadata metaData = (OptionSetMetadata)response.OptionSetMetadata;
return metaData.Options
.Where(o => o.Value == optionSetValue)
.Select(o => o.Label.UserLocalizedLabel.Label)
.FirstOrDefault();
}
catch { }
return null;
}
}
RetrieveOptionSetRequest and RetrieveOptionSetResponse are on Microsoft.Xrm.Sdk.Messages.
Call it like this:
string label = service.GetOptionSetLabel("wim_continent", 102730000);
If you are going to be querying the same option set multiple times, I recommend that you write a method that returns the OptionSetMetadata instead of the label; then query the OptionSetMetadata locally. Calling the above extension method multiple times will result in the same query being executed over and over.

Unable to Retrieve “two option” values on plugin - CRM 2011 [duplicate]

This question already has answers here:
Retrieving "two option" field value on the plugin in CRM 2011
(4 answers)
Closed 9 years ago.
I'm unable to retrieve "two option" field's selected value on plugin using the following code
bool? update = entity.GetAttributeValue<bool?>("new_updatecontacts");
bool update = entity.GetAttributeValue<bool>("new_updatecontacts");
if (update)
{
..................
}
Is there any other way of retrieving the same? I have already posted the same question, but did not get a definite answer, so am asking again.
By default, a plugin only contains the values for fields that have been added/updated. For other events you get other properties but let's go with that for now.
So if you want to be sure you have a value, you need to run off to CRM to get a copy.
var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
var serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
var service = serviceFactory.CreateOrganizationService(context.InitiatingUserId);
var target = context.InputParameters["Target"] as Entity;
if (!target.Contains("new_updatecontacts"))
{
target = service.Retrieve(target.LogicalName, target.Id, new ColumnSet(new [] { "new_updatecontacts", "other_required_fields_here" });
}
//now you know it is present
It is worth checking if it is there first as it saves a server hit.

Resources