set auto_incremented primary key explicitly while inserting the record in JDO - jdo

Enity primary key is an auto_incrimented ID in JDO
#Persistent(primaryKey = "true", valueStrategy = IdGeneratorStrategy.IDENTITY)
#Column(name = "ID")
private Long id;
When I am inserting any record, it's primary key ID is being set implicitly as auto_incremented.
I have a requirement in which I want set this ID (PK) using setter(setId()) explicitly while inserting the record.
Can we do this?

No. As comments say, you either use IDENTITY strategy (so its set by the datastore), or you set it yourself. You can't have both

Related

Devexpress xaf many to many relationship oid key Name Change

I want to set many to many relationship oid key name.
In many to many relationship Oid is created automatically but on database side I want to change oid name to custom name.
For Example;
If I try to create Person and Task many to many relation. Third table attributes in below;
KomutTanim (FK to Makine)
Makine (FK to KomutTanim)
OID (PK, guid)** (I want to set this key name??)**
Tell me how can I do. I added sample code in below
[Association("Relation.KomutListesi_Makine",typeof(KomutTanim),UseAssociationNameAsIntermediateTableName = true),XafDisplayName("Makine Komutları")]
public XPCollection<KomutTanim> Komutlar
{
get
{
return GetCollection<KomutTanim>(nameof(Komutlar));
}
}
[Association("Relation.KomutListesi_Makine", typeof(Makine), UseAssociationNameAsIntermediateTableName = true), XafDisplayName("Makineler")]
public XPCollection<Makine> MasterId
{
get
{
return GetCollection<Makine>(nameof(MasterId));
}
}
You can customize XPO metadata or manually create a persistent class for your intermediate table. These approaches are illustrated in the How to implement a many-to-many relationship with an intermediate table ticket.
The solution with customizing XPO metadata uses XAF APIs to access an XPClassInfo instance via the XPDictionary property. You can access XPDictionary using only XPO methods as illustrated at How to get an XPClassInfo instance. Also, you can manually create a ReflectionDictionary instance (ReflectionDictionary is an XPDictionary descendant) as described in the How to create persistent metadata on the fly and load data from an arbitrary table article.
XPDictionary dictionary = new ReflectionDictionary();
XPClassInfo intermediateClassInfo = dictionary.GetClassInfo(typeof(KomutTanim)).FindMember(nameof(KomutTanim.MasterId)).IntermediateClass;
intermediateClassInfo.FindMember("Oid").AddAttribute(new PersistentAttribute("MyName"));
string conn = "My connection string";
IDataStore store = XpoDefault.GetConnectionProvider(conn, AutoCreateOption.SchemaAlreadyExists);
IDataLayer dl = new SimpleDataLayer(dictionary, store);
XpoDefault.DataLayer = dl;

Azure table 'Merge' does not replace fields for which value passed is null (ex:Nullable<Date> field) C#

Azure Table 'Merge' does not merge the value of date if the date value for that record exists in the table and if we explicitly pass null to that Nullable field on merging.
I cannot use 'Replace' because the TableEntity defined in code is just a subset of the actual table with core fields defined and initialized. Replace will remove other dynamic fields added to it.
What you're observing is expected behavior of Merge Entity operation. From the documentation:
Any properties with null values are ignored by the Merge Entity
operation. All other properties will be updated.
A property cannot be removed with a Merge Entity operation. To remove
a property from an entity, replace the entity by calling the Update
Entity operation.
Apart from String data type where you can set the value as null, other data types do not support null. Setting a value of null on those attributes would simply mean you do not want to store them in the entity.
I guess the only option available to you is Replace (Update) the entity but based on the information you provided, it looks like you can't really use that option.
This is the solution.so far
Entity is the current updated record which needs to be replaced in the table.(Entity record has subset of the fields in the table for which null values are passed).
Any optimization or suggestions are welcome.
Code Snippet
TableQuery<DynamicTableEntity> rangeQuery = new TableQuery<DynamicTableEntity>().Where(
TableQuery.CombineFilters(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, Entity.PartitionKey),
TableOperators.And, TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.Equal, Entity.RowKey)));
DynamicTableEntity CurrTblRec = table.ExecuteQuery(rangeQuery).FirstOrDefault();
if (CurrTblRec != null)
{
OperationContext OpContext = new OperationContext();
DynamicTableEntity EntityDyn = new DynamicTableEntity();
IDictionary<string, EntityProperty> EntityKV = TableEntity.WriteUserObject(Entity, OpContext);
Dictionary<string, EntityProperty> ExtraFldLt = CurrTblRec.Properties.Where(x => !EntityKV.ContainsKey(x.Key)).ToDictionary(x => x.Key, x => x.Value);
EntityDyn.ReadEntity(EntityKV, OpContext);
foreach (var AdditionalField in ExtraFldLt)
EntityDyn.Properties.Add(AdditionalField);
EntityDyn.PartitionKey = Entity.PartitionKey;
EntityDyn.RowKey = Entity.RowKey;
EntityDyn.ETag = "*";
TableOperation ReplaceEntity = TableOperation.Replace(EntityDyn);
tblRes = table.Execute(ReplaceEntity);
}
else
{
TableOperation insertOperation = TableOperation.Insert(Entity);
table.Execute(insertOperation);
}

Greendao, creating a nonincrement (user-defined) primary key

Is it possible in Greendao to create a non-increment Primary Key.
So that i can specify the value each time i insert data.
Schema is :
private static void addTargetNew(Schema schema){
Entity target = schema.addEntity("Target");
target.addStringProperty("TARGET_ID").unique();
}
Delete Query :
List<Target> tList = tDao.queryBuilder().where(Properties.TARGET_ID.eq(id)).list();
if(tList != null){
Target t = tList.get(0);
tDao.delete(t);
}
Where datatype of id is String.
Also before, downvoting, reporting, what ever the hell problem you might be having regarding this question PLEASE specify the reason and give me a chance for explaination.
No. The documentation says:
… entities must have a long or Long property as their primary key

EF Code First - Set or infulence the foreign key reference names

I have read many posts about how to specify the foreign key name in relationships, no problems there. What I would like to know though, is there a way to change how the primary keys and relationships are named?
For instance, you have a User table with UserId as the primary key. The primary key is called PK_User_1788CC4C07020F21 (or something like that) by the EF code first database generation. Or you have a reference from your User table to your UserVersion table and that is called UserVersion_User by EF. I would like to have the primary key called something like PK_User and the foreign reference something like FK_UserVersion_User.
Is there a way to do this? Some convention override or actually being able to specify the text?
Thanks.
Update:
Based on the answer and link bellow I did the following in my Seed method. It's kinda brute force, but I recon that it can be refined, especially if you create the fluent entity type configuration files etc with a generator. The same could be done for the foreign key reference names.
protected override void Seed(TodoDataContext context)
{
FixIndexes(context, "User");
FixIndexes(context, "UserStats");
FixIndexes(context, "UserRole");
FixIndexes(context, "UserVersion");
FixIndexes(context, "UserUserRoleVersion");
}
private void FixIndexes(TodoDataContext context, string tableName)
{
const string renamePrimaryKeySql = #"
DECLARE #TableName NVARCHAR(128)
DECLARE #IndexName NVARCHAR(128)
DECLARE #OldName NVARCHAR(128)
DECLARE #NewName NVARCHAR(128)
SELECT #TableName = '{0}'
SELECT #IndexName = C.CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK ,INFORMATION_SCHEMA.KEY_COLUMN_USAGE C
WHERE pk.TABLE_NAME = #TableName
AND CONSTRAINT_TYPE = 'PRIMARY KEY'
AND C.TABLE_NAME = PK.TABLE_NAME
AND C.CONSTRAINT_NAME = PK.CONSTRAINT_NAME
SELECT #OldName = #TableName + '.' + #IndexName
SELECT #NewName = 'PK_' + #TableName
exec sp_rename #OldName, #NewName, 'INDEX'";
context.Database.ExecuteSqlCommand(string.Format(renamePrimaryKeySql, tableName));
No there is no way to change these names unless you manually drop them in custom initializer and create them again. EF doesn't have pluggable conventions so you cannot override them.

Set foreign key value in business entity data model

I have table SublocationTbl that have SubLocationName and LocationId(this field is foreign key from table LocationTbl), and I have business entity data model
I know that the foreign key dosen't appear in the business entity
my problrm is: how can I set the value of locationId when I need to add new subLocation?
IF you want to see the foreign key it self you must use .NET framework 4 not less in .NET 3.5 you'll find a reference to foreign key's class not the foreign key it self
Store s = new Store();
User u=s.User;//bring referance of the user with foreign key .net 3.5 & 4
int i = s.User_ID;//bring the user_id forein key .net 4
Something like this...?
using(var db = new myDbContext())
{
var myNewSubLocation = new SubLocation();
myNewSubLocation.LocationID = 12345; //put ur value here
db.SubLocations.Add(myNewSubLocation);
db.SubmitChanges();
}

Resources