Update entity columns iterating through col list using LINQ - linq

I can get column list from the table using LINQ like this:
OrderDataContext ctx = new OrderDataContext();
var cols = ctx.Mapping.MappingSource
.GetModel( typeof( OrderDataContext ) )
.GetMetaType( typeof( ProductInformation ) )
.DataMembers;
This gives me the list of columns, so I can do this:
foreach ( var col in cols )
{
// Get the value of this column from another table
GetPositionForThisField( col.Name );
}
So this all works, I can iterate through column list and pull the values for those columns from an another table (since the column names are the keys in that another table), so I don't have to do switch....or lot of if...then...
Now the question:
After I get these values, how do I populate the entity in order to save it back? I would normally go like this:
ProductInformation info = new ProductInformation();
info.SomeField1 = val1;
info.SomeField2 = val2;
ctx.ProductInformation.InsertOnSubmit( info );
ctx.SubmitChanges();
But how to use the same column collection from above to populate the columns while iterating over that, when there is no such thing as:
info["field1"].Value = val1;
Thanks.

Just fetch the object that you want to modofy, set the property and call SubmitChanges. There is no need to create a new object and insert it. The Context tracks your changed properties and generates the update statement accordingly. In your case you may want to set the properties via reflection rather than manually since you are reading them from another table.

You'll need to use reflection. Assuming you can get the PropertyInfo from the metadata:
PropertyInfo property = GetPropertyForThisField(col.Name);
property.SetValue(info, val1, null);

Related

Laravel Save Multiple Data to 1 column

So I have 2 variable for storing the selected time of the user ('time_to' and 'time_from) with these sample data('7:30','8:00')
How can I save these two into 1 column('c_time') so it would look like this('7:30-8:00')?
if i understand you correctly, you can create a column of string (varchar) type. and then create the data for your column like this :
$time_to = '7:30';
$time_from= '8:00';
$colValueToBeStored = "(".$time_to."-".$time_from.")";
then just put $colValueToBeStored inside your column.
and to reverse it:
$colValueToBeStored = "(7:30-8:00)";
$res = explode("-",str_replace([")","("],"",$colValueToBeStored));
$time_to = $res[0];
$time_from = $res[1];
define your c_time column type as JSON, that way you can store multiple values, as it will be easier to retrieve as well. Like,
...
$cTime['time_to'] = "7:30";
$cTime['time_from'] = "8:00";
$cTimeJson = json_encode($cTime);
// save to db
...

LINQ - Join only one attribute with whole schema onf another entity

I have two entities smtracks and tracks_registration I write the following linq
var track = from tracksData in sqlEntities.smtracks
join track_registrationData in sqlEntities.tracks_registration on tracksData.TracksID equals track_registrationData.FkTrackId
where tracksData.TracksID == 35 && track_registrationData.TuneCode == 5982234E
select new
{
Tunecode = track_registrationData.TuneCode
};
now i just need this one attribute Tunecode from the other table and rest i want to have the whole schema of smtracks selected. The only way i know is that I select all the attributes in the LINQ above like
select new
{
Tunecode = track_registrationData.TuneCode
TracksID = smtracks.TracksID
SongTitle = smtracks.SongTitle
.
.
.
.
.
};
and there are a lot of attributes, isn't there a simpler way to select the entire schema of one table and the just one attribute from other.
If you don't mind have extra parameter to hold the smtracks, then you can write like this :-
select new
{
smtracks=tracksData ,
Tunecode = track_registrationData.TuneCode
};
Later on you can get the value like smtracks.TracksID and so on.

Create a string collection from CheckedListBox.CheckedItems using LINQ

I have used the Entity framework to populate a checked list box. I want to get the names of the checked items as a string collection so that they can then be used as a filter for another LINQ query.
I populate the list box like this...
_eventTypesCheckedList.DataSource = this._dataContext.tblEventTypes.OrderBy(ev => ev.EventTypeName);
_eventTypesCheckedList.DisplayMember = "EventTypeName";
This is how I'm failing to get the string collection...
var types = from eType in ((_eventTypesCheckedList.CheckedItems) as IEnumerable< tblEventType > )
select new string( eType.EventTypeName.ToCharArray() );
Any help would be great.
Cast your CheckItems collection using .Cast<Type>() extension method:
_eventTypesCheckedList.CheckedItems.Cast<tblEventType>()

LINQ Select with multiple tables fields being writeable

I'm new to LINQ and I'm doing pretty well until now, but now stuck with this.
I've a LINQ object bounded to a DataGridView to let the user edit is contains.
for simple one table query, it go fine, but how to build a LINQ query with multiple table, so the result will still be read/write?
Here a example of what I mean:
GMR.Data.GMR_Entities GMR = new GMR.Data.GMR_Entities();
var dt = from Msg in GMR.tblMessages
join lang in GMR.tblDomVals on 1 equals 1//on Msg.pLangueID equals lang.ID
select Msg;
// select new {lang.DescrFr, Msg.Message,Msg.pLangueID } ;
this.dataGridView1.DataSource = dt;
In this simple query, if I return only "Msg" with the select statement, the grid can be edited. But if I replace the select statement with select new {lang.DescrFr, Msg.Message,Msg.pLangueID } ; the grid will be readable only.
I can easily understand that this is due because the query result is a anonymous type.
But is there a way to let the table tblMessage being writable?
try creating your own class, for example
public class MsgLangInfo
{
public string langDescFr{get;set;}
public int pLangueID{get;set;}
}
And at the select statement create an object of this class with new like below
select new MsgLangInfo {
langDescFr = lang.DescrFr,
langDescFr = Msg.Message,Msg.pLangueID
} ;
This way you can avoid the anonymous type problem.
You need to select the originals rows and explicitly set the grid columns.

LINQ: How to perform an update like UPDATE <T> SET Update(<T>, <T>) SELECT FROM clause in LINQ?

I want to update and insert some records based on a csv I read. The insert is not a problem, but how to update a bunch of data in a single statement? I have not clear how to join them.
Update Item
Set
Name = t.Name
From
Item i, TextFile t
Where
i.ItemNo = t.ItemNo
For the Name = t.Name I created an private Item UpdateItem(Item originalItem, Item newItem) in which the logic for updating is present.
I want to know to to call this functions and perform an db.SubmitChanges() with the changed records.
Any help appreciated.
I'm making the assumption that TextFile is an in memory collection of objects that you've read from the CSV file and Items is a Table in the data context from your database. In that case I don't think you will be able to do an actual join without first fetching all of the items from the database into an in memory collection as well -- which may be a costly operation. The sample below selects just those items and its matching new name from the text file into a new collection, then iterates through that collection and sets the name on the item. It won't use your UpdateItem method.
var textFile = ...collection of objects from CSV...
var textIDs = textFile.Select( t => t.ItemNo );
using (var db = new DataContext())
{
var toUpdate = db.Items
.Where( i => textIDs.Contains( i.ItemNo ) )
.ToList() // <--- this will force the query
.Select( i => new
{
Item = i,
NewName = textFile.Where( t => t.ItemNo == i.ItemNo )
.Single()
.Name
});
foreach (var item in toUpdate)
{
item.Item.Name = item.NewName;
}
db.SubmitChanges();
}

Resources