Linq to SQL intellisense has no knowledge of tables within the datacontext object - sql

I can successfully connect to the database with my datacontext object. I am able to read and write to the database successfully, however I can't use the same syntax that others appear to be using.
For example, when I want data from a table, I have to do something like this:
db = new UserDataDataContext(WebConfigurationManager.ConnectionStrings["UserData"].ConnectionString);
IQueryable Users = db.GetTable<User>();
I'd like to be able to write linq queries like how I see others doing them:
db = new UserDataDataContext(WebConfigurationManager.ConnectionStrings["UserData"].ConnectionString);
var query = from u in db.User
where u.UserName == "Test"
select u;
But intellisense does not recognize User as an property of db, and thus won't compile. Intellisense doesn't show any properties that look related to tables or entities of my database.
Here is the error message I am getting:
'System.Data.Linq.DataContext' does not contain a definition for 'User' and no extension method 'User' accepting a first argument of type 'System.Data.Linq.DataContext' could be found (are you missing a using directive or an assembly reference?)
Here is a rundown of what I am doing:
I used the database designer, dragged the tables in that I wanted.
Then I saved it as a dbml file.
It then created the new class that extends dataContext for me, named UserDataDataContext. I then instantiate a new instance of UserDataDataContext named db, passing in my connection string from Web.config.
Then I try to write a linq query referencing table names as properties of the db object, but it does not recognize them.
I can't seem to find what I am doing wrong compared to all of the examples I've read. Any ideas?

I'm sure you have the following variable declaration somewhere:
// variable is of type System.Data.Linq.DataContext
DataContext db;
Change it to:
// variable is now of the appropriate subclass's type
UserDataDataContext db;
If db is a local variable and you can afford to inline the initialization and declaration together, it would be even better to use implicit typing instead:
// db is implicitly of type UserDataDataContext
var db = new UserDataDataContext(WebConfigurationManager.ConnectionStrings["UserData"].ConnectionString);
C# is a safe and statically typed language. Although the object referred to by your reference will indeed, at run-time, have the properties you are expecting, the compiler won't let this compile because these properties don't exist on the variable's type.

Related

AliasToBean DTO with known type

All the examples I am finding for using the AliasToBean transformer use the sessions CreateSqlQuery method rather than the CreateQuery method. They also only return the basic value types, and not any object's of the existing mapped types.
I was hoping it would be possible that my DTO have a property of one of my mapped Domain objects, like below, but I am not getting traction. I get the following exception:
Could not find a setter for property '0' in class 'namespace.DtoClass'
My select looks like the following on my mapped classes (I have confirmed the mappings pull correctly):
SELECT
fcs.MeasurementPoint,
fcs.Form,
fcs.MeasurementPoint.IsUnscheduled as ""IsVisitUnscheduled"",
fcs.MultipleEntryAllowed
FROM FormCollectionSchedule fcs
My end query will be more complex, but I wanted to confirm if this AliasToBean method can return mapped domain objects as well as basic field values from tables retrieved via sql.
the query execution looks like the following:
var result = session.CreateQuery(hqlQuery.ToString())
.SetResultTransformer(NHibernate.Transform.Transformers.AliasToBean(typeof (VisitFormCollectionResult)))
.List<VisitFormCollectionResult>();
note: the VisitFormCollectionResult DTO has more properties, but I wanted to know if I could populate the domain object properties matching the names
update found my problem! I have to explicitly alias each of the fields. once I added an alias, even though the member property on the class matched my DTO's property name, the hydration of the object worked correctly.
The answer to my own question was that each of the individual fields in the select needed an explicit alias matching the property, regardless if the field name already matched the property name of the DTO object:
SELECT
fcs.MeasurementPoint as "MeasurementPoint",
fcs.Form as "Form",
fcs.MeasurementPoint.IsUnscheduled as "IsVisitUnscheduled",
fcs.MultipleEntryAllowed as "MultipleEntryAllowed"
FROM FormCollectionSchedule fcs

How to manually instantiate ActiveRecord truncated objects?

Working with ActiveRecord and JRuby, I try to invoke a stored procedure on a Database. Using the underlying Java Library I reached a point where I have a hash with the columns specified in the select.
Now I'd like to use this hash to have ActiveRecord models, but I'd like them to look like if I did a classic Model.select(columns).all (with only the columns values, errors when trying to reach the other ones and readonly).
There must be something inside of AR to do this but I can't find anything and all my search leads to all the basic "fetch" tutorials ...
OK so I kept digging in Rails code and figured out my answer was the instantiate method.
The idea is if you are inside a model called MyModel and do this
object = instantiate(value1: 1, value2: 'ok')
you will have an instance of the MyModel class with theses attributes defined. If the model is supposed to have more columns, they are not defined. The object is readonly.

CF9 ORM Populating an entity with an object

I am using Model-Glue/Coldspring for a new application and I thought I would throw CF9 ORM into the mix.
The only issue I am having right now is with populating an entity with an object. More or less the code below verifies that only one username can exist. There is some other logic that is not displayed.
My first thought was to using something like this:
var entity = entityload('UserAccount' ,{UserName=arguments.UserAccount.getUserName()},"true")
entity = arguments.UserAccount;
How ever this does not work the way that I expected. Is it even possible to populate an entity with an object or do I need to use the setters?
Not sure if this is what you're looking for. If you have...
component persistent="true" entityName="Foo"
{
property a;
property b;
}
You can pass a struct in the 2nd param to init the entity (added in CF9.0.1 I believe)
EntityNew("Foo", {a="1",b="2"});
To populate Foo with another object, you can use the Memento pattern, and implement a GetMemento() function to your object that returns a struct of all its properties.
EntityNew("Foo", bar.getMemento());
However, CF does NOT call your custom setters! If you want to set them using setters, you may add calls to the setters in your init() constructor, or use your MVC framework of choice to populate the bean. In Model-Glue, it is makeEventBean().
Update: Or... Here's hack...
EntityNew("Foo", DeserializeJSON(SerializeJSON(valueObject)));
Use this at your own risk. JSON might do weird things to your numbers and the 'yes','no','true','false' strings. :)
Is it even possible to populate an entity with an object or do I need to use the setters?
If you mean "Is it possible to create load an ORM Entity from an instance of that persistent CFC that already exists and has properties set?", then yes you can using EntityLoadByExample( object,[unique] )
entity = EntityLoadByExample( arguments.userAccount,true );
This assumes the userAccount CFC has been defined as persistent, and its username value has been set before being passed in (which seems to be the case in your situation).
Bear in mind that if any other properties have been set in the object you are passing, including empty strings, they will be used as filters to load the entity, so if they do not exactly match a record in your database, nothing will be loaded.

Why isn't this Linq query on Dictionary<TKey, TValue> working as DataSource

I have the following in VB:
Dim sources = From source In importSources Select New With _
{.Type = source.Key, .Source = source.Value.Name}
dgridSourceFiles.DataSource = sources
When I debug, sources shows an in-memory query and has 2 records within. Yet the datagrid view will not show the records.
So why won't this work? suggestions can be either VB or C#...
Update
When I use:
Dim sources = (From source In importSources Select New With _
{.Type = source.Key, .Source = source.Value.Name}).ToList()
...the datasource is displayed.
Your LINQ query is lazily evaluated and implements the IEnumerable<T> interface only (as far as I know), which means its results are not established until an enumerator calls MoveNext somewhere (as happens within a foreach loop, for example).
It seems the DataSource property does not enumerate its contents in this way. It's completely expecting an implementation of IList (or one of a few other interfaces—see below) so that it can access items by index. This is used internally by the control for sorting, filtering, etc. With this in mind, it's likely that all setting the DataSource property does is check the object's type to see whether it implements any of the supported interfaces. So I don't think the DataSource property is designed to deal with this type of object (a lazily evaluated query) at all.
Now, that ToList call populates a List<T> with the results of your query; this does implement IList and can therefore be used as the DataSource.
My understanding is that the reason DataSource is typed merely as object is that it expects any of the following interfaces:
IList
IListSource (in which case the IListSource.GetList method is used together with the DataMember property to provide data to the control)
IBindingList (which propagates changes in the list to the control for UI updates)
IBindingListView (like BindingSource)
This is according to the MSDN documentation.
You may need to call DataBind after setting the source. Try:
dgridSourceFiles.DataSource = sources
dgridSourceFiles.DataBind()

Specifying properties to be updated in linq query

I want to be able to specify the properties to get populated/updated in the linq expression.
Something in the following fashion:
Proxy.UpdateEmployee(List<string> propertiesNames)
Proxy.GetEmployee() //inside the method populate only certain properties
The return values must be of known type(no anonymous types accepted).
DLINQ enable to select by specifying properties' names but the result is IQueryable interface and I'm unable to AsEnumerable() it in order to build the known type query afterwards.
You have to use reflection to modify instance properties by name.
So wherever you're updating your object with LINQ you need to do something like this:
foreach (string propName in propertiesNames)
{
PropertyInfo prop = this.GetType().GetProperty(propName);
prop.SetValue(valueForProp);
}