Hi all I have a horrid database I gotta work with and linq to sql is the option im taking to retrieve data from. anywho im trying to reuse a function by throwing in a different table name based on a user selection and there is no way to my knowledge to modify the TEntity or Table<> in a DataContext Query.
This is my current code.
public void GetRecordsByTableName(string table_name){
string sql = "Select * from " + table_name;
var records = dataContext.ExecuteQuery</*Suppossed Table Name*/>(sql);
ViewData["recordsByTableName"] = records.ToList();
}
I want to populate my ViewData with Enumerable records.
You can call the ExecuteQuery method on the DataContext instance. You will want to call the overload that takes a Type instance, outlined here:
http://msdn.microsoft.com/en-us/library/bb534292.aspx
Assuming that you have a type that is attributed correctly for the table, passing that Type instance for that type and the SQL will give you what you want.
As casperOne already answered, you can use ExecuteQuery method first overload (the one that asks for a Type parameter). Since i had a similar issue and you asked an example, here is one:
public IEnumerable<YourType> RetrieveData(string tableName, string name)
{
string sql = string.Format("Select * FROM {0} where Name = '{1}'", tableName, name);
var result = YourDataContext.ExecuteQuery(typeof(YourType), sql);
return result;
}
Pay attention to YourType since you will have to define a type that has a constructor (it can't be abstract or interface). I'd suggest you create a custom type that has exactly the same attributes that your SQL Table. If you do that, the ExecuteQuery method will automatically 'inject' the values from your table to your custom type. Like that:
//This is a hypothetical table mapped from LINQ DBML
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.ClientData")]
public partial class ClientData : INotifyPropertyChanging, INotifyPropertyChanged
{
private int _ID;
private string _NAME;
private string _AGE;
}
//This would be your custom type that emulates your ClientData table
public class ClientDataCustomType
{
private int _ID;
private string _NAME;
private string _AGE;
}
So, on the former example, the ExecuteQuery method would be:
var result = YourDataContext.ExecuteQuery(typeof(ClientDataCustomType), sql);
Related
I have a JSON value stored in SQL Server. I want to retrieve that JSON value and bind it to C# property (which is deserialized to desired entity). I want to know what would be the best practice to do that effectively? Right now, I'm doing like this:
Public class Employee
{
public int Id;
public string Name;
public int Age;
}
Public class EmployeeData
{
public string JsonEmployeeText {get;set;} // Binding the json string from database
public List<Employee> Employees { get { return JsonConvert.DeserializeObject<Employee>(JsonEmployeeText );}} //Converting the retrieved json string from Database to c# entity
}
I guess we should not do any sort of database logic on getters as it can sometimes delay the process of initialization in case we need to use this we need to make sure we enable the lazy loading
I'm facing this (at least for me) interesting task: getting a SQL insert statement from a POJO like object. Let me say I don't need to add a framework between my Scala application and the DB because I just need to insert data into a single DB table.
So, supposing the attributes of my class are named equally to those of the DB table, I'd like to use Scala reflection in order to get from a class like this one
class MyDataObj {
var a:Int = 345
var b:Boolean = false
var c:Double = 1243.98
var d:String = "A random string"
}
a SQL insert statement like this
INSERT INTO table_a (a, b, c, d) values (345, false, 1243.98, 'A random String');
Well, what we need is
1) access to the class attributes
2) access to the attribute types
3) access to the attribute values of the object instance
In order to get something like this
List( ("a","Int",345), ("b","Boolean",false), ("c","Double",1243.98), ... )
that will be easy to transform into what we want.
Up to now, I've just found out how to access to the attributes names
val columns = typeOf[MyDataObj].members.view.filter{_.isTerm}.
filter{!_.isMethod}.map{_.name}.toList
How can I get the rest I need?
Thanks as usual for supporting me.
In your case, you can use the following codes:
val o = new MyDataObj
val attributes = o.getClass.getDeclaredMethods.filter {
_.getReturnType != Void.TYPE
}.map {
method => (method.getName, method.getReturnType, method.invoke(o))
}
Here I use getDeclaredMethods to get the public methods in the MyDataObj. You need to notice that getDeclaredMethods can not get methods in its parent class.
For MyDataObj, getDeclaredMethods will return the following methods:
public double MyDataObj.c()
public boolean MyDataObj.b()
public java.lang.String MyDataObj.d()
public int MyDataObj.a()
public void MyDataObj.c_$eq(double)
public void MyDataObj.d_$eq(java.lang.String)
public void MyDataObj.b_$eq(boolean)
public void MyDataObj.a_$eq(int)
So I add a filter to filter out irrelevant methods.
Is there any way to address/refer to a SQL SERVER table, by its Unique Index rather its TableName ?
my Application is using multiple html tables, which are acutally within a form,
for CRUD opporations,(more R/U than Create or delete) of an Existing SQL Table.
now... that i need to mix two separated tables, in same update-form (that's my first 'mix')
as i am using Jquery to pass parameters to C# code behind, so it will take care of the
update opporations, and will be able to differentiate the source of the update post/request
and i do know, i could address the table by its TableName,
i just wanted to make sure, as i was searching for some information on the web,
i've encountred results with the Terms sql server 2005... table index or id,
though all results seem to have something to do with, what i can call, some kind of "manipulation", in oreder to create some indexing system /schema (i think it's like hdds has a FAT table)
and I Emphasize "Create",cause I was actualy looking for an existing /built in, numeric value for a "TableID", just the same as a Table has rows and each row has its row IDENTITY - Column.
so at this point i am turning back to the real question at the top .
so that's what i came up with aventually : a simple struct + a class to hold values for database
public class DBMetaDetails
{
public struct DbTable
{
public DbTable(string tableName, int tableId): this()
{
this.Name = tableName;
this.ID = tableId;
}
public string HtmlOutput;
public string Name { get; private set; }
public int ID { get; private set; }
}
}
public sealed class tblsIDs
{
public const int firstTbl= 1, SecondTbl = 2;
}
another class should be for table names
public sealed class tblsNames
{
public const string firstTbl= "firstTbl", SecondTbl = "SecondTbl";
}
another that will hold tables columns names ...etc
I have this code:
#Column(name = "foo")
#ReadTransformer(transformerClass=transformer.class)
private Date foo;
public static class transformer implements AttributeTransformer {
#Override
public void initialize(AbstractTransformationMapping atm) {
}
#Override
public Object buildAttributeValue(Record record, Object o, Session sn) {
}
}
My question is, how do I get the value to transform (from column foo) inside of buildAttributeVaule? It is not inside the record array.
You need one or more #WriteTransformer to write the fields you want selected (and thus get them selected), #Column is not used with a transformation mapping.
However, if you just have a single column, then just use a converter instead, #Convert,
http://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Mapping/Basic_Mappings/Default_Conversions_and_Converters
First check that the SQL generated is reading in the "foo" column by turning on logging. If it is, then check that the database is returning "foo" and not "FOO" - java is case sensitive on string looksups. It could be that "FOO" is in the record instead of "foo".
I'm trying to create a dynamic type in .Net.
I want to get a group of Key Value pairs from a DB table and create a new type of object that has a Property-Value relation.
Example:
If I have a row in the table that has a field that says "Licence Plate" and the other field says "STKOVFL". I want to create an object that has a Property called Licence_Plate, and returns the String "STKOVFL".
Is it possible with introspection?
Best Regards!
Here is an very simple example of what your trying to do.
public class ExampleD : DynamicObject
{
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = null;
if (binder.Name == "Licence_Plate")
result = "STKOVFL";
return result != null;
}
}
Console.WriteLine(d.License_Plate);