Search Results

Search found 6205 results on 249 pages for 'linq to nhibernate'.

Page 52/249 | < Previous Page | 48 49 50 51 52 53 54 55 56 57 58 59  | Next Page >

  • Linq to sql Error "Data at the root level is invalid " for nullable xml column

    - by Mukesh
    I have Created a table like CREATE TABLE [dbo].[tab1]( [Id] [int] NOT NULL, [Name] [varchar](100) NOT NULL, [Meta] [xml] NULL, CONSTRAINT [PK_tab1] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] When I am doing linq to sql query to fetch a data it throw an error "data at the root level is invalid linq". In further investigation I come to know that the meta column is null in that case. In real it is nullable Do I have to remove the nullable and set some blank root node as default or there is some another way to get rid of the error. My linq Query which throws error var obj1= (from obj in dbContext.tab1s where obj.id== 123 select obj).FirstOrDefault<Tab1>();

    Read the article

  • Linq and Lamba Expressions - while walking a selected list perform an action

    - by Prescott
    Hey, I'm very new to linq and lamba expressions. I'm trying to walk a collection, and when I find an item that meets some criteria I'd like to add that to another separate collection. My linq to walk the collection looks like this (this works fine): From i as MyCustomItem In MyCustomItemCollection Where i.Type = "SomeType" Select i I need each of the select items to then be added to a ListItemCollection, I know I can assign that linq query to a variable, and then do a for each loop adding a new ListItem to the collection, but I'm trying o find a way to add each item to the new ListItemcollection while walking, not a second loop. Thanks ~P

    Read the article

  • NHibernate.Linq to Criteria API translation help needed

    - by Arnis L.
    I'm not sure how to add paging to this: Session.Linq<Article>() .Where(art => art.Tags.Any(t => t.Name == tag)).ToList(). So i decided to use Criteria API. var rowCount = Session.CreateCriteria(typeof(Article)) .SetProjection(Projections.RowCount()).FutureValue<Int32>(); var res = Session.CreateCriteria(typeof(Article)) .Add(/* any help with this? :) */) .SetFirstResult(page * pageSize) .SetMaxResults(pageSize) .AddOrder(new Order("DatePublish", true)) .Future<Article>(); totalCount = rowCount.Value; Any help appreciated.

    Read the article

  • Set the property hibernate.dialect error message

    - by user281180
    I am having the following error when configuring mvc3 and Nhibernate. Can anyone guide me what I have missed please. the dialect was not set. Set the property hibernate.dialect. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: NHibernate.HibernateException: The dialect was not set. Set the property hibernate.dialect. Source Error: Line 16: { Line 17: NHibernate.Cfg.Configuration configuration = new NHibernate.Cfg.Configuration(); Line 18: configuration.AddAssembly(System.Reflection.Assembly.GetExecutingAssembly()); Line 19: sessionFactory = configuration.BuildSessionFactory(); Line 20: } My web.config is as follows: <configSections> <section name="cachingConfiguration"type="Microsoft.Practices.EnterpriseLibrary.Caching.Configuration.CacheManagerSettings,Microsoft.Practices.EnterpriseLibrary.Caching"/> <section name="log4net"type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/> <section name="hibernate-configuration"type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"/ <appSettings> <add key="BusinessObjectAssemblies" value="Keeper.API"></add> <add key="ConnectionString" value="Server=localhost\SQLSERVER2005;Database=KeeperDev;User=test;Pwd=test;"></add> <add key="ClientValidationEnabled" value="true"/> <add key="UnobtrusiveJavaScriptEnabled" value="true"/> </appSettings> <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2"> <session-factory> <property name="dialect">NHibernate.Dialect.MsSql2000Dialect</property> <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property> <property name="connection.connection_string">Server=localhost\SQLServer2005;Database=KeeperDev;User=test;Pwd=test;</property> <property name="proxyfactory.factory_class">NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property> </session-factory> </hibernate-configuration>

    Read the article

  • Easiest way to retrofit retry logic on LINQ to SQL migration to SQL Azure

    - by Pat James
    I have a couple of existing ASP .NET web forms and MVC applications that currently use LINQ to SQL with a SQL Server 2008 Express database on a Windows VPS: one VPS for both IIS and SQL. I am starting to outgrow the VPS's ability to effectively host both SQL and IIS and am getting ready to split them up. I am considering migrating the database to SQL Azure and keeping IIS on the VPS. After doing initial research it sounds like implementing retry logic in the data access layer is a must-do when adopting SQL Azure. I suspect this is even more critical to implement in my situation where IIS will be on a VPS outside of the Azure infrastructure. I am looking for pointers on how to do this with the least effort and impact on my existing code base. Is there a good retry pattern that can be applied once at the LINQ to SQL data access layer, as opposed to having to wrap all of my LINQ to SQL operations in try/catch/wait/retry logic?

    Read the article

  • LINQ to SQL Web Application Best Practices

    - by derek
    In my experience building web applications, I've always used a n-tier approach. A DAL that gets data from the db and populates the objects, and BLL that gets objects from the DAL and performs any business logic required on them, and the website that gets it's display data from the BLL. I've recently started learning LINQ, and most of the examples show the queries occurring right from the Web Application code-behinds(it's possible that I've only seen overly simplified examples). In the n-tier architectures, this was always seen as a big no-no. I'm a bit unsure of how to architect a new Web Application. I've been using the Server Explorer and dbml designer in VS2008 to create the dbml and object relationships. It seems a little unclear to me if the dbml would be considered the DAL layer, if the website should call methods within a BLL, which then would do the LINQ queries, etc. What are some general architecture best practices, or approaches to creating a Web Application solution using LINQ to SQL?

    Read the article

  • A couple of questions about NHibernate's GuidCombGenerator

    - by Eyvind
    The following code can be found in the NHibernate.Id.GuidCombGenerator class. The algorithm creates sequential (comb) guids based on combining a "random" guid with a DateTime. I have a couple of questions related to the lines that I have marked with *1) and *2) below: private Guid GenerateComb() { byte[] guidArray = Guid.NewGuid().ToByteArray(); // *1) DateTime baseDate = new DateTime(1900, 1, 1); DateTime now = DateTime.Now; // Get the days and milliseconds which will be used to build the byte string TimeSpan days = new TimeSpan(now.Ticks - baseDate.Ticks); TimeSpan msecs = now.TimeOfDay; // *2) // Convert to a byte array // Note that SQL Server is accurate to 1/300th of a millisecond so we divide by 3.333333 byte[] daysArray = BitConverter.GetBytes(days.Days); byte[] msecsArray = BitConverter.GetBytes((long) (msecs.TotalMilliseconds / 3.333333)); // Reverse the bytes to match SQL Servers ordering Array.Reverse(daysArray); Array.Reverse(msecsArray); // Copy the bytes into the guid Array.Copy(daysArray, daysArray.Length - 2, guidArray, guidArray.Length - 6, 2); Array.Copy(msecsArray, msecsArray.Length - 4, guidArray, guidArray.Length - 4, 4); return new Guid(guidArray); } First of all, for *1), wouldn't it be better to have a more recent date as the baseDate, e.g. 2000-01-01, so as to make room for more values in the future? Regarding *2), why would we care about the accuracy for DateTimes in SQL Server, when we only are interested in the bytes of the datetime anyway, and never intend to store the value in an SQL Server datetime field? Wouldn't it be better to use all the accuracy available from DateTime.Now?

    Read the article

  • ASP.NET MVC 3 Linq uppercase or lowercase database search

    - by user1495557
    I need immediate help. ): and i know little english. ASP.NET MVC 3 Linq uppercase or lowercase contains search Example: string metin="baris"; var IcerikAra = (from icerik in Context.dbDokumanEditor join kategori in Context.dbDokumanKategori on icerik.KategoriID equals kategori.KategoriID where icerik.Icerik.toLower().Contains(metin) select new { KategoriID=kategori. KategoriAd=kategori.KategoriAd }).ToList(); Exception: StackTrace: at System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommandentityCommand, CommandBehavior behavior) at System.Data.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues) at System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption) at System.Data.Objects.ObjectQuery`1.System.Collections.Generic.IEnumerable.GetEnumerator() at System.Data.Entity.Internal.Linq.InternalQuery`1.GetEnumerator() at System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable.GetEnumerator() at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source) at Plus.Areas.DokumanEditor.Controllers.DokumanController.DokumanIcerikAramaBaslat(String metin) Error Message: An error occurred while executing the command definition. See the inner exception for details. thanks..

    Read the article

  • Date Filtered Collections without Functions

    - by madcapnmckay
    Hi, I have an entity similar to the below: public class Entity { public List<DateItem> PastDates { get; set; } public List<DateItem> FutureDates { get; set; } } public class DateItem { public DateTime Date { get; set; } /* * Other Properties * */ } Where PastDates and FutureDates are both mapped to the same type/table. I have been trying to find a way to have the Past and Future properties mapped automagically by Nhibernate. The closest I came was where clause on the mapping as follows HasMany(x => x.PastDates) .AsBag().Cascade .AllDeleteOrphan() .KeyColumnNames.Add("EventId").Where("Date < currentdate()") .Inverse(); Where currentdate is a UDF. I do not want to have these database specific functions if I can avoid it, mostly because i can't then test my DAL with SQLite as it doesn't support functions or stored procedures. At the moment I am building the past and future collections using Criteria and adding to my DTO manually. Anyone know how this could be achieved without using any UDFs? Many thanks,

    Read the article

  • Nhibernate join on a table twice

    - by Zuber
    Consider the following Class structure... public class ListViewControl { public int SystemId {get; set;} public List<ControlAction> Actions {get; set;} public List<ControlAction> ListViewActions {get; set;} } public class ControlAction { public string blahBlah {get; set;} } I want to load class ListViewControl eagerly using NHibernate. The mapping using Fluent is as shown below public UIControlMap() { Id(x => x.SystemId); HasMany(x => x.Actions) .KeyColumn("ActionId") .Cascade.AllDeleteOrphan() .AsBag() .Cache.ReadWrite().IncludeAll(); HasMany(x => x.ListViewActions) .KeyColumn("ListViewActionId") .Cascade.AllDeleteOrphan() .AsBag() .Cache.ReadWrite().IncludeAll(); } This is how I am trying to load it eagerly var baseActions = DetachedCriteria.For<ListViewControl>() .CreateCriteria("Actions", JoinType.InnerJoin) .SetFetchMode("BlahBlah", FetchMode.Eager) .SetResultTransformer(new DistinctRootEntityResultTransformer()); var listViewActions = DetachedCriteria.For<ListViewControl>() .CreateCriteria("ListViewActions", JoinType.InnerJoin) .SetFetchMode("BlahBlah", FetchMode.Eager) .SetResultTransformer(new DistinctRootEntityResultTransformer()); var listViews = DetachedCriteria.For<ListViewControl>() .SetFetchMode("Actions", FetchMode.Eager) .SetFetchMode("ListViewActions",FetchMode.Eager) .SetResultTransformer(new DistinctRootEntityResultTransformer()); var result = _session.CreateMultiCriteria() .Add("listViewActions", listViewActions) .Add("baseActions", baseActions) .Add("listViews", listViews) .SetResultTransformer(new DistinctRootEntityResultTransformer()) .GetResult("listViews"); Now, my problem is that the class ListViewControl get the correct records in both Actions and ListViewActions, but there are multiple entries of the same record. The number of records is equal to the number of joins made to the ControlAction table, in this case two. How can I avoid this? If I remove the SetFetchMode from the listViews query, the actions are loaded lazily through a proxy which I don't want.

    Read the article

  • SImplifying with LINQ - Basic selection

    - by baron
    Hello foreach (var person in peopleList.Where(person => person.FirstName == "Messi")) { selectPeople.Add(person); } I am just wondering if there is any way to simplify this using LINQ. Like rather than look at all the people I was trying to use LINQ to just fill a list with the "Messi"'s... was trying something like... var selectPeople = peopleList.Select(x=>x.FirstName=="Messi"); Then I could just add everyone in that list without a check. But it doesn't quite work as planned. Maybe there's no point simplifying that expression. But the question seemed worthwhile just to strengthen my LINQ knowledge.

    Read the article

  • Is the order of params important in NHibernate?

    - by Blake Blackwell
    If I have an int parameter followed by a string parameter in a sproc I get the following error: Input string was not in the correct format However, if I switch those parameters in the sproc than I get the result set I expect. Are params sorted by data type, or do I have to do anything special in my config file? I've included my code for reference: Config File <?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="NHibernateDemo" namespace="NHibernateDemo.Domain"> <class name="Blake_Test" table="Blake_Test"> <id name="TestId" column="TESTID"></id> <property name="TestName" column="TESTNAME" /> <loader query-ref="GetBlakeTest"/> </class> <sql-query name="GetBlakeTest" callable="true"> <return class="Blake_Test" /> call procedure AREA51.NHIBERNATE_TEST.GetBlakeTest(:int_TestId, :vch_TestName) </sql-query> </hibernate-mapping> Sproc Code: PROCEDURE GetBlakeTest ( ret_cursor OUT SYS_REFCURSOR, int_testid integer, vch_testname varchar2 ) AS BEGIN OPEN ret_cursor FOR SELECT TestId, TestName FROM blake_test WHERE testid = int_testid ORDER BY TestName DESC; END GetBlakeTest; END NHIBERNATE_TEST; Executing Code: IQuery query1 = session.GetNamedQuery( "GetBlakeTest" ); query1.SetParameter( "int_TestId", 1 ); query1.SetParameter( "vch_TestName", "TEST" ); IList<Blake_Test> mystuff = query1.List<Blake_Test>();

    Read the article

  • Starting with NHibernate

    - by George
    I'm having major difficulties to start off with NHiberante. Main problems: Where my hbm.xml files should reside? I create a Mappings folder but I received an error "Could not find xxx.hbm.xml file." I tried to load the specific class through the dialect cf.AddClass(typeof(xxx)); but it still gives me the same error (the files are marked as embebed resources. Also I'm having major problems in connection to it. I stopped trying to use the cfg xml file and tried a more direct approach with a library I have here. Configuration cfg = new Configuration(); cfg.AddClass(typeof(Tag)); ISessionFactory sessions = cfg.BuildSessionFactory(); AgnosticConnectionHandler agch = new AgnosticConnectionHandler("xxx","xxx","geo_biblio","localhost", 5432,DatabaseInstance.PostgreSQL); ISession sessao = sessions.OpenSession(agch.GetConnection); ITransaction tx = sessao.BeginTransaction(); Tag tag1 = new Tag(); tag1.NomeTag = "Teste Tag NHibernate!!!"; sessao.Save(tag1); tx.Commit(); sessao.Close(); Any tips for me? I'm getting the exception in line 2 of this code, and still not sure what to do. Any help is appreciated. Thanks

    Read the article

  • LINQ DataLoadOptions - Retrieval of data via Fulltext/Broken Foreign Key Relationship

    - by Alex
    I've hit a brick wall: I have an SQL Function: FUNCTION [dbo].[ContactsFTS] (@searchtext nvarchar(4000)) RETURNS TABLE AS RETURN SELECT * FROM Contacts INNER JOIN CONTAINSTABLE(Contacts, *, @searchtext) AS KEY_TBL ON Contacts.Id = KEY_TBL.[KEY] which I am calling via LINQ public IQueryable<ContactsFTSResult> SearchByFullText(String searchText) { return db.ContactsFTS(searchText); } I am projecting the ContactsFTSResult collection into a List<Contact> which is then given to my viewmodel. Here is the problem: My Contacts table (and therefore the Contact object created via LINQ to SQL) has multiple FK relationships to other information, such as Contact.BillingAddressId is an FK to an Address.Id. That information is missing after I do the fulltext search (e.g. if I try to access Contact.BillingAddress it is null). Can I add this information somehow via DataLoadOptions? I tried LoadWith<Contact>(c => c.BillingAddress) but this doesn't work, I assume because of the fact that I'm calling the function instead of doing the whole query via LINQ.

    Read the article

  • How can I solve this NHibernate Querying in an n-tier architecture?

    - by Tyler Wright
    I've hit a wall with trying to decouple NHibernate from my services layer. My architecture looks like this: web - services - repositories - nhibernate - db I want to be able to spawn nhibernate queries from my services layer and possibly my web layer without those layers knowing what orm they are dealing with. Currently, I have a find method on all of my repositories that takes in IList<object[]> criteria. This allows me to pass in a list of criteria such as new object() {"Username", usernameVariable}; from anywhere in my architecture. NHibernate takes this in and creates a new Criteria object and adds in the passed in criteria. This works fine for basic searches from my service layer, but I would like to have the ability to pass in a query object that my repository translates into an NHibernate Criteria. Really, I would love to implement something like what is described in this question: Is there value in abstracting nhibernate criterion. I'm just not finding any good resources on how to implement something like this. Is the method described in that question a good approach? If so, could anyone provide some pointers on how to implement such a solution?

    Read the article

  • "Session is Closed!" - NHibernate

    - by Alexis Abril
    This is in a web application environment: An initial request is able to successfully complete, however any additional requests return a "Session is Closed" response from the NHibernate framework. I'm using a HttpModule approach with the following code: public class MyHttpModule : IHttpModule { public void Init(HttpApplication context) { context.EndRequest += ApplicationEndRequest; context.BeginRequest += ApplicationBeginRequest; } public void ApplicationBeginRequest(object sender, EventArgs e) { CurrentSessionContext.Bind(SessionFactory.Instance.OpenSession()); } public void ApplicationEndRequest(object sender, EventArgs e) { ISession currentSession = CurrentSessionContext.Unbind( SessionFactory.Instance); currentSession.Dispose(); } public void Dispose() { } } SessionFactory.Instance is my singleton implementation, using FluentNHibernate to return an ISessionFactory object. In my repository class, I attempt to use the following syntax: public class MyObjectRepository : IMyObjectRepository { public MyObject GetByID(int id) { using (ISession session = SessionFactory.Instance.GetCurrentSession()) return session.Get<MyObject>(id); } } This allows code in the application to be called as such: IMyObjectRepository repo = new MyObjectRepository(); MyObject obj = repo.GetByID(1); I have a suspicion my repository code is to blame, but I'm not 100% sure on the actual implementation I should be using. I found a similar issue on SO here. I too am using WebSessionContext in my implementation, however, no solution was provided other than writing a custom SessionManager. For simple CRUD operations, is a custom session provider required apart from the built in tools(ie WebSessionContext)?

    Read the article

  • Performance concern when using LINQ "everywhere"?

    - by stiank81
    After upgrading to ReSharper5 it gives me even more useful tips on code improvements. One I see everywhere now is a tip to replace foreach-statements with LINQ queries. Take this example: private Ninja FindNinjaById(int ninjaId) { foreach (var ninja in Ninjas) { if (ninja.Id == ninjaId) return ninja; } return null; } This is suggested replaced with the following using LINQ: private Ninja FindNinjaById(int ninjaId) { return Ninjas.FirstOrDefault(ninja => ninja.Id == ninjaId); } This looks all fine, and I'm sure it's no problem regarding performance to replace this one foreach. But is it something I should do in general? Or might I run into performance problems with all these LINQ queries everywhere?

    Read the article

  • Databinding multiple tables linq query to gridview?

    - by Curtis White
    My question is how can I display a linq query in a gridview that has data from multiple tables AND allow the user to edit some of the fields or delete the data from a single table? I'd like to do this with either a linqdatasource or a linq query. I'm aware I can set the e.Result to the query on the selecting event. I've also been able to build a custom databound control for displaying the linq relations (parent.child). However, I'm not sure how I can make this work with delete? I'm thinking I may need to handle the delete event with custom code.

    Read the article

  • nhibernate : Repository Session Management

    - by frosty
    At the moment my repository has 2 constructors. When i call these from my mvc website i am alway calling first constructor and thus opening a new session. Should i been passing in the session. How should i be doing this. public CompanyRepository() { _session = NHibernateHelper.OpenSession(); } public CompanyRepository(ISession session) { _session = session; } public class NHibernateHelper { private static ISessionFactory _sessionFactory; private static ISessionFactory SessionFactory { get { if (_sessionFactory == null) { var configuration = new Configuration(); configuration.Configure(); configuration.AddAssembly(typeof(UserProfile).Assembly); configuration.SetProperty(NHibernate.Cfg.Environment.ConnectionStringName, System.Environment.MachineName); _sessionFactory = configuration.BuildSessionFactory(); } return _sessionFactory; } } public static ISession OpenSession() { return SessionFactory.OpenSession(); } } I'm using the Ninject IOC container ( very new to me ). I have the following container. How would i bind the ISession to the CompanyRepository. private class EStoreDependencies : NinjectModule { public override void Load() { Bind<ICompanyRepository>().To<CompanyRepository>(); Bind<IUserProfileRepository>().To<UserProfileRepository>(); Bind<IAddressRepository>().To<AddressRepository>(); Bind<IRolesService>().To<AspNetRoleProviderWrapper>(); Bind<IUserService>().To<AspNetMembershipProviderWrapper>(); Bind<ICurrentUserSerivce>().To<DefaultCurrentUserSerivce>(); Bind<IPasswordService>().To<AspNetMembershipProviderWrapper>(); Bind<IStatusResponseRepository>().To<StatusResponseRepository>(); Bind<ICategoryRepository>().To<CategoryRepository>(); Bind<IProductRepository>().To<ProductRepository>(); } }

    Read the article

  • Ordering by formula fields in NHibernate

    - by Darin Dimitrov
    Suppose that I have the following mapping with a formula property: <class name="Planet" table="planets"> <id name="Id" column="id"> <generator class="native" /> </id> <!-- somefunc() is a native SQL function --> <property name="Distance" formula="somefunc()" /> </class> I would like to get all planets and order them by the Distance calculated property: var planets = session .CreateCriteria<Planet>() .AddOrder(Order.Asc("Distance")) .List<Planet>(); This is translated to the following query: SELECT Id as id0, somefunc() as formula0 FROM planets ORDER BY somefunc() Desired query: SELECT Id as id0, somefunc() as formula0 FROM planets ORDER BY formula0 If I set a projection with an alias it works fine: var planets = session .CreateCriteria<Planet>() .SetProjection(Projections.Alias(Projections.Property("Distance"), "dist")) .AddOrder(Order.Asc("dist")) .List<Planet>(); SQL: SELECT somefunc() as formula0 FROM planets ORDER BY formula0 but it populates only the Distance property in the result and I really like to avoid projecting manually over all the other properties of my object (there could be many other properties). Is this achievable with NHibernate? As a bonus I would like to pass parameters to the native somefunc() SQL function. Anything producing the desired SQL is acceptable (replacing the formula field with subselects, etc...), the important thing is to have the calculated Distance property in the resulting object and order by this distance inside SQL.

    Read the article

  • LINQ query needs either ascending or descending in the same query

    - by Sir Psycho
    Is there anyway this code can be refactored? The only difference is the order by part. Idealy I'd like to use a delegate/lamda expression so the code is reusable but I don't know how to conditionally add and remove the query operators OrderBy and OrderByDescending var linq = new NorthwindDataContext(); var query1 = linq.Customers .Where(c => c.ContactName.StartsWith("a")) .SelectMany(cus=>cus.Orders) .OrderBy(ord => ord.OrderDate) .Select(ord => ord.CustomerID); var query2 = linq.Customers .Where(c => c.ContactName.StartsWith("a")) .SelectMany(cus => cus.Orders) .OrderByDescending(ord => ord.OrderDate) .Select(ord => ord.CustomerID);

    Read the article

  • How to manage sessions in NHibernate unit tests?

    - by Ben
    I am a little unsure as to how to manage sessions within my nunit test fixtures. In the following test fixture, I am testing a repository. My repository constructor takes in an ISession (since I will be using session per request in my web application). In my test fixture setup I configure NHibernate and build the session factory. In my test setup I create a clean SQLite database for each test executed. [TestFixture] public class SimpleRepository_Fixture { private static ISessionFactory _sessionFactory; private static Configuration _configuration; [TestFixtureSetUp] // called before any tests in fixture are executed public void TestFixtureSetUp() { _configuration = new Configuration(); _configuration.Configure(); _configuration.AddAssembly(typeof(SimpleObject).Assembly); _sessionFactory = _configuration.BuildSessionFactory(); } [SetUp] // called before each test method is called public void SetupContext() { new SchemaExport(_configuration).Execute(true, true, false); } [Test] public void Can_add_new_simpleobject() { var simpleObject = new SimpleObject() { Name = "Object 1" }; using (var session = _sessionFactory.OpenSession()) { var repo = new SimpleObjectRepository(session); repo.Save(simpleObject); } using (var session =_sessionFactory.OpenSession()) { var repo = new SimpleObjectRepository(session); var fromDb = repo.GetById(simpleObject.Id); Assert.IsNotNull(fromDb); Assert.AreNotSame(simpleObject, fromDb); Assert.AreEqual(simpleObject.Name, fromDb.Name); } } } Is this a good approach or should I be handling the sessions differently? Thanks Ben

    Read the article

  • NHibernate. DTO -> Domain

    - by Andrew Kalashnikov
    Hello guys. I've got SOA which processing data for diff clients(asp,sl). The base of this design is domains of my business model. For transporting,showing it to clients I use DTO. For mapping domain to DTO I use AutoMapper. Now I should persist new entities from clients. I want use my DTO's at this scenario too. So i've got some questions as I'm not much familiar with this design 1) Is it a good practice build DTO on client and send it to web-service on the wire? MayBe i should pass my domains? 2) Is it possible have several DTO's to one domain (one show at grid, and one to save). For saving I need set all nonprimitive props at client. 3) DTO - to Domain. If I've got int can I use AutoMapper to generate NHibernate Proxy for this ID, or I should do i manually. Your expierence and practice are very interesting. Thanks for answer!!!

    Read the article

  • Linq ChangeConflictException (ASP.NET MVC) - occurs when submitting DataContext changes

    - by Alex
    System.Data.Linq.ChangeConflictException: 2 of X updates failed. at System.Data.Linq.ChangeProcessor.SubmitChanges(ConflictMode failureMode) at System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode) at PROJECT.Controllers.HomeController.ClickProc(Int32 id, String code, String n) This is what I get very often. This action is done thousands of times a day, and I get this exception about once every 5 seconds. From what I understand it happens when something changes in the database in the period between creating DataContext and updating it. Am I right? What's the problem here and how can I fix it?

    Read the article

  • Inspection of Insert Statement When Using LINQ's SubmitChanges

    - by Code Sherpa
    Hi. I want to see what my insert statement would look like as if I was wiring up an text-based ADO.NET command. How do I do this? I have been following the below link: http://damieng.com/blog/2008/07/30/linq-to-sql-log-to-debug-window-file-memory-or-multiple-writers And have added the DebugTextWriter class to my project. So, now, in my code I have the following which doesn't really do anything and I don't think its right: using(WorkbookDataContext dc = _conn.GetContext()) { if(profile.ProfileId > 0) { dc.Profiles.Attach(profile, true); } else { dc.Profiles.InsertOnSubmit(profile); } dc.Log = new DebugTextWriter(); #if DEBUG dc.Log = new System.IO.StreamWriter("linq-to-sql.log") { AutoFlush = true }; #endif dc.SubmitChanges(); } Any ideas what I am doing wrong and/or how to inspect my LINQ insert statement correctly? Thanks

    Read the article

< Previous Page | 48 49 50 51 52 53 54 55 56 57 58 59  | Next Page >