Multi Mapping in Dapper - dapper

Using dapper. when I evaluate this:
var trains =
conn.Query<Train, TrainDriver, Train>(
"Select T.TrainId,T.OperatorId,T.TrainDescriptor,T.DriverId,TD.TrainDriverId,TD.Name,TD.Salary from trains as T" +
"Inner Join TrainDrivers as TD on (T.DriverId = TD.TrainDriverId)" +
"Where T.TrainId = #id", (t, td) =>
{
t.Driver = td;
return t;
}, new {id = id}, null, true, "TrainDriverId");
It seems I am getting a SQLException : {"The multi-part identifier \"T.DriverId\" could not be bound.\r\nThe multi-part identifier \"T.TrainId\" could not be bound.\r\nThe multi-part identifier \"T.TrainId\" could not be bound.\r\nThe multi-part identifier \"T.OperatorId\" could not be bound.\r\nThe multi-part identifier \"T.TrainDescriptor\" could not be bound.\r\nThe multi-part identifier \"T.DriverId\" could not be bound."}
These fields all exist, and if I strip out the SQL and run the query seperately in SQL Manager, it works...
Any thoughts?

You are just missing some spaces in the SQL query. Try:
var trains =
conn.Query<Train, Driver, Train>(
"Select T.TrainId,T.OperatorId,T.TrainDescriptor,T.DriverId,TD.TrainDriverId,TD.Name,TD.Salary from trains as T" +
" Inner Join TrainDrivers as TD on (T.DriverId = TD.TrainDriverId)" +
" Where T.TrainId = #id", (t, td) =>
{
t.Driver = td;
return t;
}, new { id = id }, null, true, "TrainDriverId");

Related

Why I am getting "Too many DML Statements" error when performing Update operation in LWC salesforce?

Why I am getting 'TOO MANY DML STATEMENTS ERROR IN THIS LINE?'
Note: Class is auraenabled(cacheable =true)
List<ABC> obj1 = new List<ABC>();
for (ABC A1 : [SELECT ID,field1, field2, field3, (SELECT Id, Name,ParentId,CreatedDate FROM Attachments WHERE Name LIKE 'something' ORDER BY CreatedDate DESC Limit 1) FROM ABC WHERE field5ID = 'field5ID' ORDER BY field1]) {
if(!A1.Attachments.isEmpty()) {
for (Attachment Att : A1.Attachments) {
MAP1.put(A1.field1,A1.Id);
if(A1.field2 = true){
A1.field2 = false;
Obj1.add(A1) ;
}
}
}
}
if(Obj1.size() > 0){
update Obj1; //GETTING ERROR ON THIS LINE
}

Ef core could not translate my custom sql server STRING_AGG function

String.Join in efcore not support and I want to get list of string with separator like sql function String_Agg
I tried to create custom sql server function but i get this error:
The parameter 'columnPartArg' for the DbFunction 'QueryHelper.StringAgg(System.Collections.Generic.IEnumerable`1[[System.String, System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=]],System.String)' has an invalid type 'IEnumerable'. Ensure the parameter type can be mapped by the current provider.
This is my function and OnModelCreatingAddStringAgg for register it in my dbcontext
public static string StringAgg(IEnumerable<string> columnPartArg, [NotParameterized] string separator)
{
throw new NotSupportedException();
}
public static void OnModelCreatingAddStringAgg(ModelBuilder modelBuilder)
{
var StringAggFuction = typeof(QueryHelper).GetRuntimeMethod(nameof(QueryHelper.StringAgg), new[] { typeof(IEnumerable<string>), typeof(string) });
var stringTypeMapping = new StringTypeMapping("NVARCHAR(MAX)");
modelBuilder
.HasDbFunction(StringAggFuction)
.HasTranslation(args => new SqlFunctionExpression("STRING_AGG",
new[]
{
new SqlFragmentExpression((args.ToArray()[0] as SqlConstantExpression).Value.ToString()),
args.ToArray()[1]
}
, nullable: true, argumentsPropagateNullability: new[] { false, false }, StringAggFuction.ReturnType, stringTypeMapping));
}
and this code run above function
_context.PersonnelProjectTimeSheets.GroupBy(c => new { c.Date.Date, c.PersonnelId, c.Personnel.PersonnelCode, c.Personnel.FirstName, c.Personnel.LastName})
.Select(c => new PersonnelProjectTimeOutputViewModel
{
IsConfirmed = c.Min(c => (int)(object)(c.IsConfirmed ?? false)) == 1,
PersonnelDisplay = c.Key.PersonnelCode + " - " + c.Key.FirstName + " " + c.Key.LastName,
PersonnelId = c.Key.PersonnelId,
Date = c.Key.Date,
ProjectName = QueryHelper.StringAgg(c.Select(x=>x.Project.Name), ", "),
TotalWorkTime = 0,
WorkTimeInMinutes = c.Sum(c => c.WorkTimeInMinutes),
});
And also i change my StringAgg method input to
string columnPartArg
and change SqlFunctionExpression of OnModelCreatingAddStringAgg to
new[]
{
new SqlFragmentExpression((args.ToArray()[0] as
SqlConstantExpression).Value.ToString()),
args.ToArray()[1]
}
and change my query code to
ProjectName = QueryHelper.StringAgg("Project.Name", ", ")
now when run my query, sql server could not recognize the Project
i guess the parameter 'columnPartArg' of dbfunction 'STRING_AGG' is varchar or nvarchar. right?
most database function or procedure has not table value as parameter.
in this case,use EFCore's 'client evaluation' is good sulution. linq like below:
_context.PersonnelProjectTimeSheets.GroupBy(c => new { c.Date.Date, c.PersonnelId, c.Personnel.PersonnelCode, c.Personnel.FirstName, c.Personnel.LastName})
.Select(c => new PersonnelProjectTimeOutputViewModel
{
IsConfirmed = c.Min(c => (int)(object)(c.IsConfirmed ?? false)) == 1,
PersonnelDisplay = c.Key.PersonnelCode + " - " + c.Key.FirstName + " " + c.Key.LastName,
PersonnelId = c.Key.PersonnelId,
Date = c.Key.Date,
ProjectName = string.Join(", ",c.Select(x=>x.Project.Name)),//Client evaluation
TotalWorkTime = 0,
WorkTimeInMinutes = c.Sum(c => c.WorkTimeInMinutes),
});

Micro ORM Dapper Could not find the key property for type

I am new to Micro-ORM i am using dapper fluent mapping and dommel I try to insert/add entries but I encounter this error "Could not find the key property for type"
here is my Code
using (IDbConnection con = new MySqlConnection(cnxStr))
{
con.Open();
equipment eqp = new equipment
{
category_id = 1,
barcode = "DDH-003",
asset_number = "45645645",
equipment_name = "DBD Dew",
equipment_description = "Thin Can",
manufacturer_id = 3,
model = "Blah",
serialnumber = "11111",
status = "Good",
service_group = "SGE",
required_pm = "Yes",
service_provider="111",
frequency = 1,
department_id = 1,
location_id = 1,
availability = "Avail",
register_id = 1,
supplier_id = 1,
conditionstatus_id = 1,
status_id = 1,
utilization_id = 3
};
int count = con.Insert<equipment>(eqp); <-- error here
if (count > 0)
{
MessageBox.Show("Successfully Added", "Successfully Added -:", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
con.Close();
}
Dapper assumes you have a column named Id in your db model, unless you specify otherwise. In this case, on the other hand, you are using an extenstion from Dapper.Contrib. For this to work you have to add a directive [key] above your primary key.

Selects from multiple tables for Activities feed

I have a social app for which I am trying to create a friend activities feed using Azure Sql Server.
I have 3 tables I want to select from:
Songs
-createdAt
-id
-userId
-trackName
-etc
Comments
-createdAt
-id
-userId
-songId
-text
Likes
-createdAt
-id
-userId
-songId
I have the users that the current user is following stored in an array named 'follows'.
How do I go about selecting the 40 most recent items from those 3 tables where userId in each table is in the follows array?
Edit:
function getActivities(userId) {
var deferred = Q.defer();
var follows = [];
getFollowing(userId).then(function (results) {
follows.push(userId);
_.each(results, function (user) {
follows.push(user.toUserId);
});
return;
}).then(function () {
var stringified = "'" + follows.join("','") + "'";
var queryString = "SELECT * FROM comments, songs, likes WHERE comments.userId IN (" + stringified + ") OR songs.userId IN (" + stringified +") OR likes.userId IN (" + stringified + ")";
var params = [];
return sqlQuery(queryString, params);
}).then(function (results) {
console.log('Activities: ', results);
deferred.resolve(results);
}, function (error) {
console.log('Error: ', error.message);
deferred.reject(error.message);
});
return deferred.promise;
}
Alright, so I dug into JOINS a little more and realized how easy it actually is once you wrap your head around it. Here is what I did to complete this:
var queryString = "SELECT TOP 50 follows.id AS followId, follows.toUserId AS followToUserId, follows.fromUserId AS followFromUserId, comments.text AS commentText, profiles.userId, profiles.username, profiles.name, profiles.profileImage, songs.trackId, songs.trackName, songs.artistName, songs.collectionName, songs.artworkUrl100, songs.caption, songs.id AS songId, activities.id AS activityId, activities.type AS activityType, activities.objectId AS activityObjectId, activities.parentType AS activityParentType, activities.parentId AS activityParentId, activities.__createdAt AS activityCreatedAt FROM activities ";
queryString += "INNER JOIN profiles ON (profiles.userId = activities.userId) ";
queryString += "LEFT JOIN songs ON (songs.id = activities.objectId AND activities.type = 'songs') OR (songs.id = activities.parentId AND activities.parentType = 'songs') ";
queryString += "LEFT JOIN comments ON (activities.type = 'comments' AND comments.id = activities.objectId) ";
queryString += "LEFT JOIN follows ON (activities.type = 'followed' AND activities.userid = follows.fromUserId) ";
queryString += "WHERE activities.userId IN (SELECT follows.toUserId AS userId FROM follows WHERE follows.fromUserId = ? AND follows.isFollowed = 'true') ";
queryString += "ORDER BY activities.__createdAt DESC";
var params = [userId];
mssql.query(queryString, params, {
success: function (results) {
_.each(results, function (result) {
//Remove columns with null or undefined values
for (var i in result) {
if (result[i] === null || result[i] === undefined) {
delete result[i];
}
}
});
response.send(200, results);
},
error: function (error) {
response.send(400, error.message);
}
});

System.DmlException: Update failed. first error: INVALID_CROSS_REFERENCE_KEY,

i am trying to update a ObjectPermissions Object in slaesforce such that a profile will get the permissions to access a object similar to other profile.
i write a code
my code segment is
PermissionSet set1 = [SELECT Id From PermissionSet
WHERE profileId = : SourceProfileId LIMIT 1] ;
PermissionSet set2 = [SELECT Id FROM PermissionSet
WHERE profileId = : TargetProfileId LIMIT 1];
List<ObjectPermissions> oo = [SELECT Id,
SObjectType,
ParentId,
PermissionsCreate,
PermissionsDelete,
PermissionsEdit,
PermissionsModifyAllRecords,
PermissionsRead,
PermissionsViewAllRecords
FROM ObjectPermissions
WHERE ParentId = : set1.id];
List<ObjectPermissions> oo1 = [SELECT ParentId,
Id,
SObjectType,
PermissionsCreate,
PermissionsDelete,
PermissionsEdit,
PermissionsModifyAllRecords,
PermissionsRead,
PermissionsViewAllRecords
FROM ObjectPermissions
WHERE ParentId = : set2.Id];
Map<String , ObjectPermissions> source_obj = new Map<String, ObjectPermissions>();
Map<String , ObjectPermissions> target_obj = new Map<String, ObjectPermissions>();
for (ObjectPermissions o : oo) {
source_obj.put(o.SObjectType, o);
}
for (ObjectPermissions o : oo1) {
target_obj.put(o.SObjectType, o);
}
ObjectPermissions target, source;
for (String s : source_obj.keySet() ) {
if (target_obj.containsKey(s)) {
target = target_obj.get(s);
source = source_obj.get(s);
System.debug('Source is:' + source);
System.debug('Target is : ' + target);
target.PermissionsCreate = source.PermissionsCreate;
target.PermissionsDelete = source.PermissionsDelete;
target.PermissionsEdit = source.PermissionsEdit;
target.PermissionsModifyAllRecords = source.PermissionsModifyAllRecords;
target.PermissionsRead = source.PermissionsRead;
target.PermissionsViewAllRecords = source.PermissionsViewAllRecords;
update target;
} else {
target = new ObjectPermissions(SObjectType = s );
source = source_obj.get(s);
target.PermissionsCreate = source.PermissionsCreate;
target.PermissionsDelete = source.PermissionsDelete;
target.PermissionsEdit = source.PermissionsEdit;
target.PermissionsModifyAllRecords = source.PermissionsModifyAllRecords;
target.PermissionsRead = source.PermissionsRead;
target.PermissionsViewAllRecords = source.PermissionsViewAllRecords;
insert target;
}
}
when the control come to this line
update target;
it is giving error
Update failed. First exception on row 0 with id 110i0000007KNEvAAO; first error: INVALID_CROSS_REFERENCE_KEY, You can't create, edit, or delete records for this permission set parent because it's associated with a profile. Parent ID: 0PSi00000009BE9: []
i am unable to figure it out why i am facing this error please some one help to resolve this error
the persmission set you are trying to update is already associated with some of your profile with id=0PSi00000009BE9
go to
https://ap1.salesforce.com/0PSi00000009BE9 and check there.

Resources