Search Results

Search found 1109 results on 45 pages for 'ado'.

Page 7/45 | < Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • What's the best way to validate EntityFramwork 4.0 classes?

    - by lsb
    Hi! I've done a fair amount of searching but I've yet to find an easy way to validate EntityFramework 4.0 entities passed accross the wire via WCF Data Services. Basically, I want to do something on the client like: Proxy.MyEntities entities = new Proxy.MyEntities( new Uri("http://localhost:2679/Service.svc")); Proxy.Vendor vendor = new Proxy.Vendor(); vendor.Code = "ABC/XYZ"; vendor.Status = "ACTIVE"; // I'd like to do something like the following: vendor.Validate(); entities.AddToVendors(vendor); entities.SaveChanges(); Any help in this regard would be greatly appreciated!

    Read the article

  • Developing your Data Access Layer with ADO.NET Entity Framework 4

    Entity Framework has evolved in the light of feedback. ADO.NET Entity Framework 4 is now better able to accommodate different development methodologies. A welcome improvement is the way that, the application designer now has a range of options in the way that Entity Framework creates the Data Access layer. Prasanna returns to Simple-Talk to explain the significance of the changes.

    Read the article

  • ADO.NET Data Services business logic processing

    a simple approach that provides business logic processing before forwarding data to the clients with ADO.NET Data Services.  read moreBy Siyamand AyubiDid you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • Utilisation de la colonne de type XML dans SQL Server 2005 avec ADO.net

    De plus en plus les développeurs, dans leurs applications, doivent faire cohabiter des données relationnelles et des données XML au sein d'une même source de données et le plus souvent optent pour la mauvaise solution. Bonjour, Je viens de finalisé avec mon premier article qui porte sur l'intégration du XML dans Sql Server et le traitement côté client avec ADO.net. Cette discussion est ouverte pour prendre vos commentaires et remarques sur l'article. le lien Cordialement ...

    Read the article

  • Protecting ADO.NET applications Part I

    Protecting ADO.NET applications Part I...Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • How do I use an ADO.NET managed provider in Excel?

    - by Eli
    I have an ADO.NET Managed Data Provider that is registered in machine.config in DbProviderFactory - It is available for use from, say, Analysis Services, so I know it is correctly registered. However, I need to be able to query the managed provider from Excel, but the managed provider doesn't appear as a choice from Data Link Properties | All Ole Db Providers. How do I get an ADO.NET Managed Data Provider to appear there, or is there another technique I need to use? Thanks in advance, Eli.

    Read the article

  • how can I future-proof migration of a ADO.net local data layer to a future web based interface (web-

    - by Greg
    Hi, BACKGROUND: I am working on a .NET WinForms application now (C#) with an ADO.net database for the data layer. QUESTION: How an I develop this now such that it would be easy to migrate to a model where the data layer is abstracted via a HTTP web-service or REST interface? For example would just use of a standard C# interface with a Factory to obtain a concrete implementation of the interface where this uses ADO.net be the best? thanks

    Read the article

  • Delphi / ADO : WHich components? TADODataSet and TADOCommand or TADOQuery ?

    - by mawg
    According to http://www.delphigroups.info/2/3/181838.html The preferred approach with ADO components is to use TADODataSet and TADOCommand. TADOQuery (and TADOTable and TADOStoredProc) are provided for compatibility. Use TADODataSet for SQL that returns result-sets and TADOCommand for SQL that does not. I am a clueless n00b - who is about to code a lot of ADO stuph. Is that correct? Which components should I use fop something which does/does not return a result?

    Read the article

  • How can I monitor the SQL commands send over my ADO connection?

    - by RRUZ
    i need intercept all the SQL commands that pass between an ADO connection component and a database server. something like the TSQLmonitor of dbExpress, but for ADO . Anybody know any third-party component that implements this functionality? UPDATE I want to do is to monitor the SQL statements programmatically (by code) from my application without using an external tool. for any database engine.

    Read the article

  • Retrieve data from an ASP.Net application using Ado.Net 2.0 disconnected model

    - by nikolaosk
    This is the second post in a series of posts regarding to ADO.Net 2.0. Have a look at the first post if you like. In this post I am going to investigate the "Disconnected" model. When I say "Disconnected" I mean Datasets . Datasets are in memory representations of tables in a particular database. A Dataset contains a Table collection and each Table collection contains a Row collection and each Row collection contains a Columns collection. So initially you connect to the database, get the data to...(read more)

    Read the article

  • Retrieve data from an ASP.Net application using ADO.Net 2.0 connected model

    - by nikolaosk
    I have been teaching Entity Framework,LINQ to SQL,LINQ to objects,LINQ to XML for some time now. I am huge fan of LINQ to Entities and I am using Entity Framework as my main data access technology. Entity framework is in the second version right now and I can accomplish most of the things I need. I am sure the guys in the ADO.Net team will implement many more features in the future. I am a strong believer that you cannot really understand the benefits of LINQ to SQL or LINQ to Entities unless you...(read more)

    Read the article

  • Silverlight 3.0 and ADO.NET data service framework(An error occurred while processing this request)

    - by ybbest
    Today , I try to write a Silverlight app that talks to SharePoint 2010 using the REST API.However after deploy the silverlight app and run the code , I got the following error.In order to fix this I need to make the target framework of your caller application to 4.0,in this case I need to use Silverlight 4.0 instead 3.0.After I have done that and redeploy the solution to the SharePoint.It works like a charm.   Exceptions details: System.Data.Services.Client.DataServiceQueryException: An error occurred while processing this request. Request version ’1.0′ is too low for the response. The lowest supported version is ’2.0′. However , if you got the error like this: Could not load type ‘System.Data.Services.Providers.IDataServiceUpdateProvider’ from assembly ‘System.Data.Services, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089′,then you need to install ADO.NET Data Services Update for .NET Framework 3.5 SP1 ,you can download here (for windowns 7 and server 2008 r2 ) or here (for windows vista of server 2008).

    Read the article

  • How do I associate Parameters to Command objects in ADO with VBScript?

    - by Krashman5k
    I have been working an ADO VBScript that needs to accept parameters and incorporate those parameters in the Query string that gets passed the the database. I keep getting errors when the Record Set Object attempts to open. If I pass a query without parameters, the recordset opens and I can work with the data. When I run the script through a debugger, the command object does not show a value for the parameter object. It seems to me that I am missing something that associates the Command object and Parameter object, but I do not know what. Here is a bit of the VBScript Code: ... 'Open Text file to collect SQL query string' Set fso = CreateObject("Scripting.FileSystemObject") fileName = "C:\SQLFUN\Limits_ADO.sql" Set tso = fso.OpenTextFile(fileName, FORREADING) SQL = tso.ReadAll 'Create ADO instance' connString = "DRIVER={SQL Server};SERVER=myserver;UID=MyName;PWD=notapassword; Database=favoriteDB" Set connection = CreateObject("ADODB.Connection") Set cmd = CreateObject("ADODB.Command") connection.Open connString cmd.ActiveConnection = connection cmd.CommandText = SQL cmd.CommandType = adCmdText Set paramTotals = cmd.CreateParameter With paramTotals .value = "tot%" .Name = "Param1" End With 'The error occurs on the next line' Set recordset = cmd.Execute If recordset.EOF then WScript.Echo "No Data Returned" Else Do Until recordset.EOF WScript.Echo recordset.Fields.Item(0) ' & vbTab & recordset.Fields.Item(1) recordset.MoveNext Loop End If The SQL string that I use is fairly standard except I want to pass a parameter to it. It is something like this: SELECT column1 FROM table1 WHERE column1 IS LIKE ? I understand that ADO should replace the "?" with the parameter value I assign in the script. The problem I am seeing is that the Parameter object shows the correct value, but the command object's parameter field is null according to my debugger.

    Read the article

  • How can I have 2 ADO access methods use the same Transaction?

    - by KevinDeus
    I'm writing a test to see if my LINQ to Entity statement works.. I'll be using this for others if I can get this concept going.. my intention here is to INSERT a record with ADO, then verify it can be queried with LINQ, and then ROLLBACK the whole thing at the end. I'm using ADO to insert because I don't want to use the object or the entity model that I am testing. I figure that a plain ADO INSERT should do fine. problem is.. they both use different types of connections. is it possible to have these 2 different data access methods use the same TRANSACTION so I can roll it back?? _conn = new SqlConnection(_connectionString); _conn.Open(); _trans = _conn.BeginTransaction(); var x = new SqlCommand("INSERT INTO Table1(ID, LastName, FirstName, DateOfBirth) values('127', 'test2', 'user', '2-12-1939');", _conn); x.ExecuteNonQuery(); //So far, so good. Adding a record to the table. //at this point, we need to do **_trans.Commit()** here because our Entity code can't use the same connection. Then I have to manually delete in the TestHarness.TearDown.. I'd like to eliminate this step //(this code is in another object, I'll include it for brevity. Imagine that I passed the connection in) //check to see if it is there using (var ctx = new XEntities(_conn)) //can't do this.. _conn is not an EntityConnection! { var retVal = (from m in ctx.Table1 where m.first_name == "test2" where m.last_name == "user" where m.Date_of_Birth == "2-12-1939" where m.ID == 127 select m).FirstOrDefault(); return (retVal != null); } //Do test.. Assert.BlahBlah(); _trans.Rollback();

    Read the article

  • How is timezone handled in the lifecycle of an ADO.NET + SQL Server DateTime column?

    - by stimpy77
    Using SQL Server 2008. This is a really junior question and I could really use some elaborate information, but the information on Google seems to dance around the topic quite a bit and it would be nice if there was some detailed elaboration on how this works... Let's say I have a datetime column and in ADO.NET I set it to DateTime.UtcNow. 1) Does SQL Server store DateTime.UtcNow accordingly, or does it offset it again based on the timezone of where the server is installed, and then return it offset-reversed when queried? I think I know that the answer is "of course it stores it without offsetting it again" but want to be certain. So then I query for it and cast it from, say, an IDataReader column to a DateTime. As far as I know, System.DateTime has metadata that internally tracks whether it is a UTC DateTime or it is an offsetted DateTime, which may or may not cause .ToLocalTime() and .ToUniversalTime() to have different behavior depending on this state. So, 2) Does this casted System.DateTime object already know that it is a UTC DateTime instance, or does it assume that it has been offset? Now let's say I don't use UtcNow, I use DateTime.Now, when performing an ADO.NET INSERT or UPDATE. 3) Does ADO.NET pass the offset to SQL Server and does SQL Server store DateTime.Now with the offset metadata? So then I query for it and cast it from, say, an IDataReader column to a DateTime. 4) Does this casted System.DateTime object already know that it is an offset time, or does it assume that it is UTC?

    Read the article

  • MySQL ADO.NET Connector & MSSQL Integration Services

    - by user1114330
    Here I am, day three... attempting to sync a data view on a Windows Vista box (64 bit) running MSSQL 2012 and Visual Studio 2010. Sanity is slipping and hunger for progress fills my attention. I went through hell trying to get the MySQL ODBC drivers to get the job but to no avail...everyone seems to be lost and all the threads I can find are solutions that do not work for me. The problem: System DSN's not being seen by SSIS. SSIS DSN Not Showing as ODBC Data Source I make the decision to try out the ADO.NET connector...and to my surprise it is actually in the selection list in data sources in SSIS. So I take off running to create a Data Flow Task, create an ADO.NET Source (a local MSSQL DB)...all is good as usual. Then I move swiftly to creating a ADO.NET Destination, enter my credentials...wow, I am selecting a database finally on my linux server! Happy thinking that I finally have figured a way to get the job done. Then I move to mappings...nope, something is wrong...I am getting an error that hurts my eyes: Pipeline component has returned HRESULT error code 0xC0208457 from a a method call. Error at Data Flow Task [ADO NET Destination [81]]: Failed to get properties of external columns. The table name you entered may not exist or you do not have SELECT permission on the table object and an alternative attempt to get column properties through connection has failed. Detailed error messages are" You have an error in your SQL syntax check the manual that corresponds to your MySQL server version for the right syntax to use near "database".tablename" at line 1. The descriptor files on path C:\Program Files (x86)\Microsoft SQL Server\110\DTS\ProviderDescriptors\ does not contain schema information for connection of type MySQL.Data.MySqlClient.MySqlConnection. So it looks like it can't the information and therefore I cannot map the tables properly. Any ideas on this would be ultra helpful...thanks in advance to All!

    Read the article

  • How to create a custom ADO Multi Dimensional Catalog with no database

    - by Alan Clark
    Does anyone know of an example of how to dynamically define and build ADO MD (ActiveX Data Objects Multidimensional) catalogs and cube definitions with a set of data other than a database? Background: we have a huge amount of data in our application that we export to a database and then query using the usual SQL joins, groups, sums etc to produce reports. The data in the application is originally in objects and arrays. The problem is the amount of data is so large the export can take 2 hours. So I am trying to figure out a good way of querying the objects in memory, either by a custom OLAP algorithm or library, or ADO MD. But I haven't been able to find an example of using ADO MD without a database behind it. We are using Delphi 2010 so would use ADO ActiveX but I imagine the ADO.NET MD is similar. I realize that if the application data was already stored in a database the problem would solve itself. Also if Delphi had LINQ capability I could query the objects and arrays that way.

    Read the article

  • How to create a custom ADO Multi Demensional Catalog with no database

    - by Alan Clark
    Does anyone know of an example of how to dynamically define and build ADO MD (ActiveX Data Objects Multidimensional) catalogs and cube definitions with a set of data other than a database? Background: we have a huge amount of data in our application that we export to a database and then query using the usual SQL joins, groups, sums etc to produce reports. The data in the application is originally in objects and arrays. The problem is the amount of data is so large the export can take 2 hours. So I am trying to figure out a good way of querying the objects in memory, either by a custom OLAP algorithm or library, or ADO MD. But I haven't been able to find an example of using ADO MD without a database behind it. We are using Delphi 2010 so would use ADO ActiveX but I imagine the ADO.NET MD is similar. I realize that if the application data was already stored in a database the problem would solve itself. Also if Delphi had LINQ capability I could query the objects and arrays that way.

    Read the article

  • SQL ADO.NET shortcut extensions (old school!)

    - by Jeff
    As much as I love me some ORM's (I've used LINQ to SQL quite a bit, and for the MSDN/TechNet Profile and Forums we're using NHibernate more and more), there are times when it's appropriate, and in some ways more simple, to just throw up so old school ADO.NET connections, commands, readers and such. It still feels like a pain though to new up all the stuff, make sure it's closed, blah blah blah. It's pretty much the least favorite task of writing data access code. To minimize the pain, I have a set of extension methods that I like to use that drastically reduce the code you have to write. Here they are... public static void Using(this SqlConnection connection, Action<SqlConnection> action) {     connection.Open();     action(connection);     connection.Close(); } public static SqlCommand Command(this SqlConnection connection, string sql){    var command = new SqlCommand(sql, connection);    return command;}public static SqlCommand AddParameter(this SqlCommand command, string parameterName, object value){    command.Parameters.AddWithValue(parameterName, value);    return command;}public static object ExecuteAndReturnIdentity(this SqlCommand command){    if (command.Connection == null)        throw new Exception("SqlCommand has no connection.");    command.ExecuteNonQuery();    command.Parameters.Clear();    command.CommandText = "SELECT @@IDENTITY";    var result = command.ExecuteScalar();    return result;}public static SqlDataReader ReadOne(this SqlDataReader reader, Action<SqlDataReader> action){    if (reader.Read())        action(reader);    reader.Close();    return reader;}public static SqlDataReader ReadAll(this SqlDataReader reader, Action<SqlDataReader> action){    while (reader.Read())        action(reader);    reader.Close();    return reader;} It has been awhile since I've really revisited these, so you will likely find opportunity for further optimization. The bottom line here is that you can chain together a bunch of these methods to make a much more concise database call, in terms of the code on your screen, anyway. Here are some examples: public Dictionary<string, string> Get(){    var dictionary = new Dictionary<string, string>();    _sqlHelper.GetConnection().Using(connection =>        connection.Command("SELECT Setting, [Value] FROM Settings")            .ExecuteReader()            .ReadAll(r => dictionary.Add(r.GetString(0), r.GetString(1))));    return dictionary;} or... public void ChangeName(User user, string newName){    _sqlHelper.GetConnection().Using(connection =>         connection.Command("UPDATE Users SET Name = @Name WHERE UserID = @UserID")            .AddParameter("@Name", newName)            .AddParameter("@UserID", user.UserID)            .ExecuteNonQuery());} The _sqlHelper.GetConnection() is just some other code that gets a connection object for you. You might have an even cleaner way to take that step out entirely. This looks more fluent, and the real magic sauce for me is the reader bits where you can put any kind of arbitrary method in there to iterate over the results.

    Read the article

  • S#harp architecture mapping many to many and ado.net data services: A single resource was expected f

    - by Leg10n
    Hi, I'm developing an application that reads data from a SQL server database (migrated from a legacy DB) with nHibernate and s#arp architecture through ADO.NET Data services. I'm trying to map a many-to-many relationship. I have a Error class: public class Error { public virtual int ERROR_ID { get; set; } public virtual string ERROR_CODE { get; set; } public virtual string DESCRIPTION { get; set; } public virtual IList<ErrorGroup> GROUPS { get; protected set; } } And then I have the error group class: public class ErrorGroup { public virtual int ERROR_GROUP_ID {get; set;} public virtual string ERROR_GROUP_NAME { get; set; } public virtual string DESCRIPTION { get; set; } public virtual IList<Error> ERRORS { get; protected set; } } And the overrides: public class ErrorGroupOverride : IAutoMappingOverride<ErrorGroup> { public void Override(AutoMapping<ErrorGroup> mapping) { mapping.Table("ERROR_GROUP"); mapping.Id(x => x.ERROR_GROUP_ID, "ERROR_GROUP_ID"); mapping.IgnoreProperty(x => x.Id); mapping.HasManyToMany<Error>(x => x.Error) .Table("ERROR_GROUP_LINK") .ParentKeyColumn("ERROR_GROUP_ID") .ChildKeyColumn("ERROR_ID").Inverse().AsBag(); } } public class ErrorOverride : IAutoMappingOverride<Error> { public void Override(AutoMapping<Error> mapping) { mapping.Table("ERROR"); mapping.Id(x => x.ERROR_ID, "ERROR_ID"); mapping.IgnoreProperty(x => x.Id); mapping.HasManyToMany<ErrorGroup>(x => x.GROUPS) .Table("ERROR_GROUP_LINK") .ParentKeyColumn("ERROR_ID") .ChildKeyColumn("ERROR_GROUP_ID").AsBag(); } } When I view the Data service in the browser like: http://localhost:1905/DataService.svc/Errors it shows the list of errors with no problems, and using it like http://localhost:1905/DataService.svc/Errors(123) works too. The Problem When I want to see the Errors in a group or the groups form an error, like: "http://localhost:1905/DataService.svc/Errors(123)?$expand=GROUPS" I get the XML Document, but the browser says: The XML page cannot be displayed Cannot view XML input using XSL style sheet. Please correct the error and then click the Refresh button, or try again later. -------------------------------------------------------------------------------- Only one top level element is allowed in an XML document. Error processing resource 'http://localhost:1905/DataServic... <error xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"> -^ I view the sourcecode, and I get the data. However it comes with an exception: <error xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"> <code></code> <message xml:lang="en-US">An error occurred while processing this request.</message> <innererror xmlns="xmlns"> <message>A single resource was expected for the result, but multiple resources were found.</message> <type>System.InvalidOperationException</type> <stacktrace> at System.Data.Services.Serializers.Serializer.WriteRequest(IEnumerator queryResults, Boolean hasMoved)&#xD; at System.Data.Services.ResponseBodyWriter.Write(Stream stream)</stacktrace> </innererror> </error> A I missing something??? Where does this error come from?

    Read the article

  • Auto-hydrate your objects with ADO.NET

    - by Jake Rutherford
    Recently while writing the monotonous code for pulling data out of a DataReader to hydrate some objects in an application I suddenly wondered "is this really necessary?" You've probably asked yourself the same question, and many of you have: - Used a code generator - Used a ORM such as Entity Framework - Wrote the code anyway because you like busy work     In most of the cases I've dealt with when making a call to a stored procedure the column names match up with the properties of the object I am hydrating. Sure that isn't always the case, but most of the time it's 1 to 1 mapping.  Given that fact I whipped up the following method of hydrating my objects without having write all of the code. First I'll show the code, and then explain what it is doing.      /// <summary>     /// Abstract base class for all Shared objects.     /// </summary>     /// <typeparam name="T"></typeparam>     [Serializable, DataContract(Name = "{0}SharedBase")]     public abstract class SharedBase<T> where T : SharedBase<T>     {         private static List<PropertyInfo> cachedProperties;         /// <summary>         /// Hydrates derived class with values from record.         /// </summary>         /// <param name="dataRecord"></param>         /// <param name="instance"></param>         public static void Hydrate(IDataRecord dataRecord, T instance)         {             var instanceType = instance.GetType();                         //Caching properties to avoid repeated calls to GetProperties.             //Noticable performance gains when processing same types repeatedly.             if (cachedProperties == null)             {                 cachedProperties = instanceType.GetProperties().ToList();             }                         foreach (var property in cachedProperties)             {                 if (!dataRecord.ColumnExists(property.Name)) continue;                 var ordinal = dataRecord.GetOrdinal(property.Name);                 var isNullable = property.PropertyType.IsGenericType &&                                  property.PropertyType.GetGenericTypeDefinition() == typeof (Nullable<>);                 var isNull = dataRecord.IsDBNull(ordinal);                 var propertyType = property.PropertyType;                 if (isNullable)                 {                     if (!string.IsNullOrEmpty(propertyType.FullName))                     {                         var nullableType = Type.GetType(propertyType.FullName);                         propertyType = nullableType != null ? nullableType.GetGenericArguments()[0] : propertyType;                     }                 }                 switch (Type.GetTypeCode(propertyType))                 {                     case TypeCode.Int32:                         property.SetValue(instance,                                           (isNullable && isNull) ? (int?) null : dataRecord.GetInt32(ordinal), null);                         break;                     case TypeCode.Double:                         property.SetValue(instance,                                           (isNullable && isNull) ? (double?) null : dataRecord.GetDouble(ordinal),                                           null);                         break;                     case TypeCode.Boolean:                         property.SetValue(instance,                                           (isNullable && isNull) ? (bool?) null : dataRecord.GetBoolean(ordinal),                                           null);                         break;                     case TypeCode.String:                         property.SetValue(instance, (isNullable && isNull) ? null : isNull ? null : dataRecord.GetString(ordinal),                                           null);                         break;                     case TypeCode.Int16:                         property.SetValue(instance,                                           (isNullable && isNull) ? (int?) null : dataRecord.GetInt16(ordinal), null);                         break;                     case TypeCode.DateTime:                         property.SetValue(instance,                                           (isNullable && isNull)                                               ? (DateTime?) null                                               : dataRecord.GetDateTime(ordinal), null);                         break;                 }             }         }     }   Here is a class which utilizes the above: [Serializable] [DataContract] public class foo : SharedBase<foo> {     [DataMember]     public int? ID { get; set; }     [DataMember]     public string Name { get; set; }     [DataMember]     public string Description { get; set; }     [DataMember]     public string Subject { get; set; }     [DataMember]     public string Body { get; set; }            public foo(IDataRecord record)     {         Hydrate(record, this);                }     public foo() {} }   Explanation: - Class foo inherits from SharedBase specifying itself as the type. (NOTE SharedBase is abstract here in the event we want to provide additional methods which could be overridden by the instance class) public class foo : SharedBase<foo> - One of the foo class constructors accepts a data record which then calls the Hydrate method on SharedBase passing in the record and itself. public foo(IDataRecord record) {      Hydrate(record, this); } - Hydrate method on SharedBase will use reflection on the object passed in to determine its properties. At the same time, it will effectively cache these properties to avoid repeated expensive reflection calls public static void Hydrate(IDataRecord dataRecord, T instance) {      var instanceType = instance.GetType();      //Caching properties to avoid repeated calls to GetProperties.      //Noticable performance gains when processing same types repeatedly.      if (cachedProperties == null)      {           cachedProperties = instanceType.GetProperties().ToList();      } . . . - Hydrate method on SharedBase will iterate each property on the object and determine if a column with matching name exists in data record foreach (var property in cachedProperties) {      if (!dataRecord.ColumnExists(property.Name)) continue;      var ordinal = dataRecord.GetOrdinal(property.Name); . . . NOTE: ColumnExists is an extension method I put on IDataRecord which I’ll include at the end of this post. - Hydrate method will determine if the property is nullable and whether the value in the corresponding column of the data record has a null value var isNullable = property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof (Nullable<>); var isNull = dataRecord.IsDBNull(ordinal); var propertyType = property.PropertyType; . . .  - If Hydrate method determines the property is nullable it will determine the underlying type and set propertyType accordingly - Hydrate method will set the value of the property based upon the propertyType   That’s it!!!   The magic here is in a few places. First, you may have noticed the following: public abstract class SharedBase<T> where T : SharedBase<T> This says that SharedBase can be created with any type and that for each type it will have it’s own instance. This is important because of the static members within SharedBase. We want this behavior because we are caching the properties for each type. If we did not handle things in this way only 1 type could be cached at a time, or, we’d need to create a collection that allows us to cache the properties for each type = not very elegant.   Second, in the constructor for foo you may have noticed this (literally): public foo(IDataRecord record) {      Hydrate(record, this); } I wanted the code for auto-hydrating to be as simple as possible. At first I wasn’t quite sure how I could call Hydrate on SharedBase within an instance of the class and pass in the instance itself. Fortunately simply passing in “this” does the trick. I wasn’t sure it would work until I tried it out, and fortunately it did.   So, to actually use this feature when utilizing ADO.NET you’d do something like the following:        public List<foo> GetFoo(int? fooId)         {             List<foo> fooList;             const string uspName = "usp_GetFoo";             using (var conn = new SqlConnection(_dbConnection))             using (var cmd = new SqlCommand(uspName, conn))             {                 cmd.CommandType = CommandType.StoredProcedure;                 cmd.Parameters.Add(new SqlParameter("@FooID", SqlDbType.Int)                                        {Direction = ParameterDirection.Input, Value = fooId});                 conn.Open();                 using (var dr = cmd.ExecuteReader())                 {                     fooList= (from row in dr.Cast<DbDataRecord>()                                             select                                                 new foo(row)                                            ).ToList();                 }             }             return fooList;         }   Nice! Instead of having line after line manually assigning values from data record to an object you simply create a new instance and pass in the data record. Note that there are certainly instances where columns returned from stored procedure do not always match up with property names. In this scenario you can still use the above method and simply do your manual assignments afterward.

    Read the article

  • WPF: How to connect to a sql ce 3.5 database with ADO.NET?

    - by EV
    Hi, I'm trying to write an application that has two DataGrids - the first one displays customers and the second one selected customer's records. I have generated the ADO.NET Entity Model and the connection property are set in App.config file. Now I want to populate the datagrids with the data from sql ce 3.5 database which does not support LINQ-TO-SQL. I used this code for the first datagrid in code behind: CompanyDBEntities db; private void Window_Loaded(object sender, RoutedEventArgs e) { db = new CompanyDBEntities(); ObjectQuery<Employees> departmentQuery = db.Employees; try { // lpgrid is the name of the first datagrid this.lpgrid.ItemsSource = departmentQuery; } catch (Exception ex) { MessageBox.Show(ex.Message); } However, the datagrid is empty although there are records in a database. It would also be better to use it in MVVM pattern but I'm not sure how does the ado.net and MVVM work together and if it is even possible to use them like that. Could anyone help? Thanks in advance.

    Read the article

  • ADO.NET Multiple simultaneous reads from an open database.

    - by Deverill
    Answer not needed - my logic was wrong and this question is invalid. Charles helped me see where I went off-tracks. Thanks I have a utility that moves data from one source to another. In the process of writing the record I check to see if it exists and do an update/insert as necessary. The difficulty I have is that as I'm writing the main record info there is a 2nd table for "custom data" that I have to check to see if it exists and do an update/insert for that as well. Example: I may be loading a pencil sharpener that may or may not exist. While I'm writing it into destination it has characteristics such as style, color, etc. and each of them may or may not exist. As written I seem to need to have 2 DataReaders open, one for the sharpener and one to check for and update color. I am new to ADO.NET, but not to programming and it's more complicated than I listed but for sanity's sake I didn't put all the details. My question is: What am I missing? You can't have 2 readers open at the same time on a connection, yet I can't close the first if I'm stepping through all products. It seems inefficient to have 2 connections, readers, etc. for this. Is there a feature of ADO.NET DBs that I'm missing? How would you do it? Thanks!

    Read the article

< Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >