Search Results

Search found 4565 results on 183 pages for 'nhibernate mapping'.

Page 73/183 | < Previous Page | 69 70 71 72 73 74 75 76 77 78 79 80  | Next Page >

  • Bulk insert of component collection in Hibernate?

    - by edbras
    I have the mapping as listed below. When I update a detached Categories item (that doesn't contain any Hibernate class as it comes from a dto converter) I notice that Hibernate will first delete ALL employer wages instances (the collection link) and then insert ALL employer wage entries ONE-BY-ONE :(... I understand that it has to delete and then insert all entries as it was completely detached. BUT, what I don't understand, why is Hibernate NOT inserting all the entries through bulk-insert?.. That is: inserting all the employer wage entries all in one SQL statement ? How can I tell Hibernate to use bulk-insert? (if possible). I tried playing with the following value but didn't see any difference: hibernate.jdbc.batch_size=30 My mapping snippet: <class name="com.sample.CategoriesDefault" table="dec_cats" > <id name="id" column="id" type="string" length="40" access="property"> <generator class="assigned" /> </id> <component name="incomeInfoMember" class="com.sample.IncomeInfoDefault"> <property name="hasWage" type="boolean" column="inMemWage"/> ... <component name="wage" class="com.sample.impl.WageDefault"> <property name="hasEmployerWage" type="boolean" column="inMemEmpWage"/> ... <set name="employerWages" cascade="all-delete-orphan" lazy="false"> <key column="idCats" not-null="true" /> <one-to-many entity-name="mIWaEmp"/> </set> </component> </component> </class>

    Read the article

  • Best practice when removing entity regarding mappedBy collections?

    - by Daniel Bleisteiner
    I'm still kind of undecided which is the best practice to handle em.remove(entity) with this entity being in several collections mapped using mappedBy in JPA. Consider an entity like a Property that references three other entities: a Descriptor, a BusinessObject and a Level entity. The mapping is defined using @ManyToOne in the Property entity and using @OneToMany(mappedBy...) in the other three objects. That inverse mapping is defined because there are some situations where I need to access those collections. Whenever I remove a Property using em.remove(prop) this element is not automatically removed from managed entities of the other three types. If I don't care about that and the following page load (webapp) doesn't reload those entities the Property is still found and some decisions might be taken that are no longer true. The inverse mappings may become quite large and though I don't want to use something like descriptor.getProperties().remove(prop) because it will load all those properties that might have been lazy loaded until then. So my currently preferred way is to refresh the entity if it is managed: if (em.contains(descriptor)) em.refresh(descriptor) - which unloads a possibly loaded collection and triggers a reload upon the next access. Is there another feasible way to handle all those mappedBy collections of already loaded entites?

    Read the article

  • C# WCF Server retrieves 'List<T>' with 1 entry, but client doesn't receive it?! Please help Urgentl

    - by Neville
    Hi Everyone, I've been battling and trying to research this issue for over 2 days now with absolutely no luck. I am trying to retrieve a list of clients from the server (server using fluentNHibernate). The client object is as follow: [DataContract] //[KnownType(typeof(System.Collections.Generic.List<ContactPerson>))] //[KnownType(typeof(System.Collections.Generic.List<Address>))] //[KnownType(typeof(System.Collections.Generic.List<BatchRequest>))] //[KnownType(typeof(System.Collections.Generic.List<Discount>))] [KnownType(typeof(EClientType))] [KnownType(typeof(EComType))] public class Client { #region Properties [DataMember] public virtual int ClientID { get; set; } [DataMember] public virtual EClientType ClientType { get; set; } [DataMember] public virtual string RegisterID {get; set;} [DataMember] public virtual string HerdCode { get; set; } [DataMember] public virtual string CompanyName { get; set; } [DataMember] public virtual bool InvoicePerBatch { get; set; } [DataMember] public virtual EComType ResultsComType { get; set; } [DataMember] public virtual EComType InvoiceComType { get; set; } //[DataMember] //public virtual IList<ContactPerson> Contacts { get; set; } //[DataMember] //public virtual IList<Address> Addresses { get; set; } //[DataMember] //public virtual IList<BatchRequest> Batches { get; set; } //[DataMember] //public virtual IList<Discount> Discounts { get; set; } #endregion #region Overrides public override bool Equals(object obj) { var other = obj as Client; if (other == null) return false; return other.GetHashCode() == this.GetHashCode(); } public override int GetHashCode() { return ClientID.GetHashCode() | ClientType.GetHashCode() | RegisterID.GetHashCode() | HerdCode.GetHashCode() | CompanyName.GetHashCode() | InvoicePerBatch.GetHashCode() | ResultsComType.GetHashCode() | InvoiceComType.GetHashCode();// | Contacts.GetHashCode() | //Addresses.GetHashCode() | Batches.GetHashCode() | Discounts.GetHashCode(); } #endregion } As you can see, I have allready tried to remove the sub-lists, though even with this simplified version of the client I still run into the propblem. my fluent mapping is: public class ClientMap : ClassMap<Client> { public ClientMap() { Table("Clients"); Id(p => p.ClientID); Map(p => p.ClientType).CustomType<EClientType>(); ; Map(p => p.RegisterID); Map(p => p.HerdCode); Map(p => p.CompanyName); Map(p => p.InvoicePerBatch); Map(p => p.ResultsComType).CustomType<EComType>(); Map(p => p.InvoiceComType).CustomType<EComType>(); //HasMany<ContactPerson>(p => p.Contacts) // .KeyColumns.Add("ContactPersonID") // .Inverse() // .Cascade.All(); //HasMany<Address>(p => p.Addresses) // .KeyColumns.Add("AddressID") // .Inverse() // .Cascade.All(); //HasMany<BatchRequest>(p => p.Batches) // .KeyColumns.Add("BatchID") // .Inverse() // .Cascade.All(); //HasMany<Discount>(p => p.Discounts) // .KeyColumns.Add("DiscountID") // .Inverse() // .Cascade.All(); } The client method, seen below, connects to the server. The server retrieves the list, and everything looks right in the object, still, when it returns, the client doesn't receive anything (it receive a List object, but with nothing in it. Herewith the calling method: public List<s.Client> GetClientList() { try { s.DataServiceClient svcClient = new s.DataServiceClient(); svcClient.Open(); List<s.Client> clients = new List<s.Client>(); clients = svcClient.GetClientList().ToList<s.Client>(); svcClient.Close(); //when receiving focus from server, the clients object has a count of 0 return clients; } catch (Exception e) { MessageBox.Show(e.Message); } return null; } and the server method: public IList<Client> GetClientList() { var clients = new List<Client>(); try { using (var session = SessionHelper.OpenSession()) { clients = session.Linq<Client>().Where(p => p.ClientID > 0).ToList<Client>(); } } catch (Exception e) { EventLog.WriteEntry("eCOWS.Data", e.Message); } return clients; //returns a list with 1 client in it } the server method interface is: [UseNetDataContractSerializer] [OperationContract] IList<Client> GetClientList(); for final references, here is my client app.config entries: <system.serviceModel> <bindings> <netTcpBinding> <binding name="NetTcpBinding_IDataService" listenBacklog="10" maxConnections="10" transferMode="Buffered" transactionProtocol="OleTransactions" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" receiveTimeout="00:10:00" sendTimeout="00:10:00"> <readerQuotas maxDepth="51200000" maxStringContentLength="51200000" maxArrayLength="51200000" maxBytesPerRead="51200000" maxNameTableCharCount="51200000" /> <security mode="Transport"/> </binding> </netTcpBinding> </bindings> <client> <endpoint address="net.tcp://localhost:9000/eCOWS/DataService" binding="netTcpBinding" bindingConfiguration="NetTcpBinding_IDataService" contract="eCowsDataService.IDataService" name="NetTcpBinding_IDataService" behaviorConfiguration="eCowsEndpointBehavior"> </endpoint> <endpoint address="MEX" binding="mexHttpBinding" contract="IMetadataExchange" /> </client> <behaviors> <endpointBehaviors> <behavior name="eCowsEndpointBehavior"> <dataContractSerializer maxItemsInObjectGraph="2147483647"/> </behavior> </endpointBehaviors> </behaviors> </system.serviceModel> and my server app.config: <system.serviceModel> <bindings> <netTcpBinding> <binding name="netTcpBinding" maxConnections="10" listenBacklog="10" transferMode="Buffered" transactionProtocol="OleTransactions" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" sendTimeout="00:10:00" receiveTimeout="00:10:00"> <readerQuotas maxDepth="51200000" maxStringContentLength="51200000" maxArrayLength="51200000" maxBytesPerRead="51200000" maxNameTableCharCount="51200000" /> <security mode="Transport"/> </binding> </netTcpBinding> </bindings> <services> <service name="eCows.Data.Services.DataService" behaviorConfiguration="eCowsServiceBehavior"> <host> <baseAddresses> <add baseAddress="http://localhost:9001/eCOWS/" /> <add baseAddress="net.tcp://localhost:9000/eCOWS/" /> </baseAddresses> </host> <endpoint address="DataService" binding="netTcpBinding" contract="eCows.Data.Services.IDataService" behaviorConfiguration="eCowsEndpointBehaviour"> </endpoint> <endpoint address="MEX" binding="mexHttpBinding" contract="IMetadataExchange" /> </service> </services> <behaviors> <endpointBehaviors> <behavior name="eCowsEndpointBehaviour"> <dataContractSerializer maxItemsInObjectGraph="2147483647" /> </behavior> </endpointBehaviors> <serviceBehaviors> <behavior name="eCowsServiceBehavior"> <serviceMetadata httpGetEnabled="True"/> <serviceThrottling maxConcurrentCalls="10" maxConcurrentSessions="10"/> <serviceDebug includeExceptionDetailInFaults="False" /> </behavior> <behavior name="MexBehaviour"> <serviceMetadata /> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> I use to run into "socket closed / network or timeout" errors, and the trace showed clearly that on the callback it was looking for a listening endpoint, but couldn't find one. Anyway, after adding the UseNetSerializer that error went away, yet now I'm just not getting anything. Oh PS. if I add all the commented out List items, I still retrieve an entry from the DB, but also still not receive anything on the client. if I remove the [UseNetDataContractSerializer] I get the following error(s) in the svclog : WARNING: Description Faulted System.ServiceModel.Channels.ServerSessionPreambleConnectionReader+ServerFramingDuplexSessionChannel WARNING: Description Faulted System.ServiceModel.Channels.ServiceChannel ERROR: Initializing[eCows.Data.Models.Client#3]-failed to lazily initialize a collection of role: eCows.Data.Models.Client.Addresses, no session or session was closed ... ERROR: Could not find default endpoint element that references contract 'ILogbookManager' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element. If I add a .Not.LazyLoad to the List mapping items, I'm back at not receiving errors, but also not receiving any client information.. Sigh! Please, if anyone can help with this I'd be extremely grateful. I'm probably just missing something small.. but... what is it :) hehe. Thanks in advance! Neville

    Read the article

  • Application connection with database persist after sucessfull transaction also.

    - by anupam3m
    Hi , I am using Spring.Data.NHibernate12 on my database level.my application connection with database is not getting released. Underneath given is Dataconfiguration.xml < ?xml version="1.0" encoding="utf-8" ? < objects xmlns="http://www.springframework.net" xmlns:db="http://www.springframework.net/database" < object id="AuditLogger" type="Risco.Rsp.Ac.Audit.AuditLogger, Risco.Rsp.Ac.Audit" singleton="false" < property name="CacheSettings" ref="CacheSettings"/ < /object < object id="CacheSettings" type="Risco.Rsp.Ac.AMAC.CacheMgmt.Utilities.UpdateEntityCacheHelper, Risco.Rsp.Ac.AMAC.CacheMgmt.Utilities" singleton="false"/ < object type="Spring.Objects.Factory.Config.PropertyPlaceholderConfigurer, Spring.Core" < <property name="ConfigSections" value="databaseSettings"/> < < db:provider id="AMACDbProvider" provider="OracleClient-2.0" connectionString="Data Source=RISCODEVDB;User ID=amsbvt; Password=amsuser1234;"/ Risco.Rsp.Ac.AMAC.Mapping Risco.Rsp.Ac.Logging.Appenders Risco.Rsp.Ac.AMAC.CacheMappings --

    Read the article

  • Lazy loading is not working for one to many

    - by Shire
    Any 1-M that use the primary key of the parent table, but any 1-M that uses a different column does not work. It generates the SQL correctly, but put the value of the key into the SQL instead of the column value I want. Example mapping: public TemplateMap() { Table("IMPORT"); LazyLoad(); Id(x => x.ImportId).Column("IMPORT_ID").GeneratedBy.Assigned(); Map(x => x.ImportSetId).Column("IMPORTSET_ID"); HasMany(x => x.GoodChildren) .Access.CamelCaseField() .KeyColumns.Add("IMPORT_ID") .Cascade.Delete() .Inverse(); HasMany(x => x.BadChildren) .Access.CamelCaseField() .KeyColumns.Add("IMPORTSET_ID") .Cascade.Delete() .Inverse(); } Lazy loading works for GoodChildren, but not for BadChildren. The SQL statement is correct for both children. But the wrong values are use. If the value of IMPORT_ID is 10 and the value of IMPORTSET_ID is 12. The value 10 will be used for the IMPORTSET_ID in the SQL for BadChildren instead of 12. Anyone have any ideas what I need to change to get BadChildren to work correctly? Note: GoodChildren links to IMPORT_ID on Template BadChildren links to IMPORTSET_ID on Template

    Read the article

  • Fluently.Configure without explicitly entering types.

    - by user86431
    I'm trying to take my fluent mapping past the basic stuff that I've found here: http://wiki.fluentnhibernate.org/Fluent_configuration Where they explicitly add each type like this: ISessionFactory localFactory = Fluently.Configure() .Database( ObjectFactory.GetInstance<SybaseConfiguration>().GetSybaseDialect( "BLAH" ) ) .Mappings( m => { m.HbmMappings .AddFromAssemblyOf<StudTestEO>(); m.FluentMappings .AddFromAssemblyOf<StudTestEO>() .AddFromAssemblyOf<StudTestEOMap>(); } ) .BuildSessionFactory(); .BuildSessionFactory(); and trying to be able to take the assembly, get a list of it's types and pass that in instead kindf like this string FullEoAssemblyFName = webAccessHdl.GetMapPath(EoAssemblyFName); string FullMapAssemblyFName = webAccessHdl.GetMapPath(MapAssemblyFName); string FullConfigFileName = webAccessHdl.GetMapPath("~/" + NHibernateConfigFileName); if (!File.Exists(FullEoAssemblyFName)) throw new Exception("GetFactoryByConfigFile, EoAssemblyFName does not exist>" + FullEoAssemblyFName + "<"); if (!File.Exists(FullMapAssemblyFName)) throw new Exception("GetFactoryByConfigFile, MapAssemblyFName does not exist>" + FullMapAssemblyFName + "<"); if (!File.Exists(FullConfigFileName)) throw new Exception("GetFactoryByConfigFile, ConfigFile does not exist>" + FullConfigFileName + "<"); Configuration configuration = new Configuration(); Assembly EoAssembly = Assembly.LoadFrom(webAccessHdl.GetMapPath(EoAssemblyFName)); Assembly MapAssembly = Assembly.LoadFrom(webAccessHdl.GetMapPath(MapAssemblyFName)); Type[] EoType = EoAssembly.GetTypes(); Type[] MapType = MapAssembly.GetTypes(); ISessionFactory localFactory = fluent.Mappings( m => { // how do i add all the types from type array here? m.FluentMappings.Add(MapAssembly).AddFromAssembly(EoAssembly); } ) .BuildSessionFactory(); To get it to load the types genericly instead of explicitly.. has anyone done this, or see any good links to articles I should look at? Thanks, E-

    Read the article

  • Question About Fk refrence in The Collection

    - by Ahmed
    Hi , i have 2 entities : ( person ) & (Address) with follwing mapping : <class name="Adress" table="Adress" lazy="false"> <id name="Id" column="Id"> <generator class="native" /> </id> <many-to-one name="Person" class="Person"> <column name="PersonId" /> </many-to-one> </class> <class name="Person" table="Person" lazy="false"> <id name="PersonId" column="PersonId"> <generator class="native" /> </id> <property name="Name" column="Name" type="String" not-null="true" /> <set name="Adresses" lazy="true" inverse="true" cascade="save-update"> <key> <column name="PersonId" /> </key> <one-to-many class="Adress" /> </set> </class> my propblem is that when i set Adrees.Person with new object of person ,The collection person.Adresses doesn't update itself . should i update every end role of the association to be updated in the two both? another thing : if i updated the Fk manually like this : Adress.PersonId it doesn't break or change association. does this is Nhibernte behavior ? thanks in advance , i am waiting for your experiencies

    Read the article

  • Model Binding with Parent/Child Relationship

    - by user296297
    I'm sure this has been answered before, but I've spent the last three hours looking for an acceptable solution and have been unable to find anything, so I apologize for what I'm sure is a repeat. I have two domain objects, Player and Position. Player's have a Position. My domain objects are POCOs tied to my database with NHibernate. I have an Add action that takes a Player, so I'm using the built in model binding. On my view I have a drop down list that lets a user select the Position for the Player. The value of the drop down list is the Id of the position. Everything gets populated correctly except that my Position object fails validation (ModelState.IsValid) because at the point of model binding it only has an Id and none of it's other required attributes. What is the preferred solution for solving this with ASP.NET MVC 2? Solutions I've tried... Fetch the Position from the database based on the Id before ModelState.IsValid is called in the Add action of my controller. I can't get the model to run the validation again, so ModelState.IsValid always returns false. Create a custom ModelBinder that inherits from the default binder and fetch the Position from the database after the base binder is called. The ModelBinder seems to be doing the validation so if I use anything from the default binder I'm hosed. Which means I have to completely roll my own binder and grab every value from the form...this seems really wrong and inefficient for such a common use-case. Solutions I think might work, I just can't figure out how to do... Turn off the validation for the Position class when used in Player. Write a custom ModelBinder leverages the default binder for most of the property binding, but lets me get the Position from the database BEFORE the default binder runs validation. So, how do the rest of you solve this? Thanks, Dan P.S. In my opinion having a PositionId on Player just for this case is not a good solution. There has to be solvable in a more elegant fashion.

    Read the article

  • NHibernateUnitOfWork + ASP.Net MVC

    - by Felipe
    Hi Guys, hows it going? I'm in my first time with DDD, so I'm begginer! So, let's take it's very simple :D I developed an application using asp.net mvc 2 , ddd and nhibernate. I have a domain model in a class library, my repositories in another class library, and an asp.net mvc 2 application. My Repository base class, I have a construct that I inject and dependency (my unique ISessionFactory object started in global.asax), the code is: public class Repository<T> : IRepository<T> where T : Entidade { protected ISessionFactory SessionFactory { get; private set; } protected ISession Session { get { return SessionFactory.GetCurrentSession(); } } protected Repository(ISessionFactory sessionFactory) { SessionFactory = sessionFactory; } public void Save(T entity) { Session.SaveOrUpdate(entity); } public void Delete(T entity) { Session.Delete(entity); } public T Get(long key) { return Session.Get<T>(key); } public IList<T> FindAll() { return Session.CreateCriteria(typeof(T)).SetCacheable(true).List<T>(); } } And After I have the spefic repositories, like this: public class DocumentRepository : Repository<Domain.Document>, IDocumentRepository { // constructor public DocumentRepository (ISessionFactory sessionFactory) : base(sessionFactory) { } public IList<Domain.Document> GetByType(int idType) { var result = Session.CreateQuery("from Document d where d.Type.Id = :IdType") .SetParameter("IdType", idType) .List<Domain.Document>(); return result; } } there is not control of transaction in this code, and it's working fine, but, I would like to make something to control this repositories in my controller of asp.net mvc, something simple, like this: using (var tx = /* what can I put here ? */) { try { _repositoryA.Save(objA); _repositoryB.Save(objB); _repositotyC.Delete(objC); /* ... others tasks ... */ tx.Commit(); } catch { tx.RollBack(); } } I've heared about NHibernateUnitOfWork, but i don't know :(, How Can I configure NHibernateUnitOfWork to work with my repositories ? Should I change the my simple repository ? Sugestions are welcome! So, thanks if somebody read to here! If can help me, I appretiate! PS: Sorry for my english! bye =D

    Read the article

  • ISQLQuery using AddJoin not loading related instance

    - by Remi Despres-Smyth
    I've got a problem using an ISQLQuery with an AddJoin. The entity I'm trying to return is RegionalFees, which has a composite-id which includes a Province instance. (This is the the instance being improperly loaded.) Here's the mapping: <class name="Project.RegionalFees, Project" table="tblRegionalFees"> <composite-id name="Id" class="Project.RegionalFeesId, project" unsaved-value="any" access="property"> <key-many-to-one class="Project.Province, Project" name="Region" access="property" column="provinceId" not-found="exception" /> <key-property name="StartDate" access="property" column="startDate" type="DateTime" /> </composite-id> <property name="SomeFee" column="someFee" type="Decimal" /> <property name="SomeOtherFee" column="someOtherFee" type="Decimal" /> <!-- Other unrelated stuff --> </class> <class name="Project.Province, Project" table="trefProvince" mutable="false"> <id name="Id" column="provinceId" type="Int64" unsaved-value="0"> <generator class="identity" /> </id> <property name="Code" column="code" access="nosetter.pascalcase-m-underscore" /> <property name="Label" column="label" access="nosetter.pascalcase-m-underscore" /> </class> Here's my query method: public IEnumerable<RegionalFees> GetRegionalFees() { // Using an ISQLQuery cause there doesn't appear to be an equivalent of // the SQL HAVING clause, which would be optimal for loading this set const String qryStr = "SELECT * " + "FROM tblRegionalFees INNER JOIN trefProvince " + "ON tblRegionalFees.provinceId=trefProvince.provinceId " + "WHERE EXISTS ( " + "SELECT provinceId, MAX(startDate) AS MostRecentFeesDate " + "FROM tblRegionalFees InnerRF " + "WHERE tblRegionalFees.provinceId=InnerRF.provinceId " + "AND startDate <= ? " + "GROUP BY provinceId " + "HAVING tblRegionalFees.startDate=MAX(startDate))"; var qry = NHibernateSessionManager.Instance.GetSession().CreateSQLQuery(qryStr); qry.SetDateTime(0, DateTime.Now); qry.AddEntity("RegFees", typeof(RegionalFees)); qry.AddJoin("Region", "RegFees.Id.Region"); return qry.List<RegionalFees>(); } The odd behavior here is that when I call GetRegionalFees (whose goal is to load just the most recent fee instances per region), it all loads fine if the Province instance is a proxy. If, however, Province is not loaded as a transparent proxy, the Province instance which is part of RegionalFees' RegionalFeesId property has null Code and Region values, although the Id value is set correctly. It looks to me like I have a problem in how I'm joining the Province class - since if it's lazy loaded the id is set from tblRegionalFees, and it gets loaded independently afterwards - but I haven't been able to figure out the solution.

    Read the article

  • MVC Persist Collection ViewModel (Update, Delete, Insert)

    - by Riccardo Bassilichi
    In order to create a more elegant solution I'm curios to know your suggestion about a solution to persist a collection. I've a collection stored on DB. This collection go to a webpage in a viewmodel. When the go back from the webpage to the controller I need to persist the modified collection to the same DB. The simple solution is to delete the stored collection and recreate all rows. I need a more elegant solution to mix the collections and delete not present record, update similar records ad insert new rows. this is my Models and ViewModels. public class CustomerModel { public virtual string Id { get; set; } public virtual string Name { get; set; } public virtual IList<PreferredAirportModel> PreferedAirports { get; set; } } public class AirportModel { public virtual string Id { get; set; } public virtual string AirportName { get; set; } } public class PreferredAirportModel { public virtual AirportModel Airport { get; set; } public virtual int CheckInMinutes { get; set; } } // ViewModels public class CustomerViewModel { [Required] public virtual string Id { get; set; } public virtual string Name { get; set; } public virtual IList<PreferredAirporViewtModel> PreferedAirports { get; set; } } public class PreferredAirporViewtModel { [Required] public virtual string AirportId { get; set; } [Required] public virtual int CheckInMinutes { get; set; } } And this is the controller with not elegant solution. public class CustomerController { public ActionResult Save(string id, CustomerViewModel viewModel) { var session = SessionFactory.CurrentSession; var customer = session.Query<CustomerModel>().SingleOrDefault(el => el.Id == id); customer.Name = viewModel.Name; // How cai I Merge collections handling delete, update and inserts ? var modifiedPreferedAirports = new List<PreferredAirportModel>(); var modifiedPreferedAirportsVm = new List<PreferredAirporViewtModel>(); // Update every common Airport foreach (var airport in viewModel.PreferedAirports) { foreach (var custPa in customer.PreferedAirports) { if (custPa.Airport.Id == airport.AirportId) { modifiedPreferedAirports.Add(custPa); modifiedPreferedAirportsVm.Add(airport); custPa.CheckInMinutes = airport.CheckInMinutes; } } } // Remove common airports from ViewModel modifiedPreferedAirportsVm.ForEach(el => viewModel.PreferedAirports.Remove(el)); // Remove deleted airports from model var toDelete = customer.PreferedAirports.Except(modifiedPreferedAirports); toDelete.ForEach(el => customer.PreferedAirports.Remove(el)); // Add new Airports var toAdd = viewModel.PreferedAirports.Select(el => new PreferredAirportModel { Airport = session.Query<AirportModel>(). SingleOrDefault(a => a.Id == el.AirportId), CheckInMinutes = el.CheckInMinutes }); toAdd.ForEach(el => customer.PreferedAirports.Add(el)); session.Save(customer); return View(); } } My environment is ASP.NET MVC 4, nHibernate, Automapper, SQL Server. Thank You!!

    Read the article

  • How to design a data model that deals with (real) contracts?

    - by Geoffrey
    I was looking for some advice on designing a data model for contract administration. The general life cycle of a contract is thus: Contract is created and in a "draft" state. It is viewable internally and changes may be made. Contract goes out to vendor, status is set to "pending" Contract is rejected by vendor. At this state, nothing can be done to the contract. No statuses may be added to the collection. Contract is accepted by vendor. At this state, nothing can be done to the contract. No statuses may be added to the collection. I obviously want to avoid a situation where the contract is accepted and, say, the amount is changed. Here are my classes: [EnforceNoChangesAfterDraftState] public class VendorContract { public virtual Vendor Vendor { get; set; } public virtual decimal Amount { get; set; } public virtual VendorContact VendorContact { get; set; } public virtual string CreatedBy { get; set; } public virtual DateTime CreatedOn { get; set; } public virtual FileStore Contract { get; set; } public virtual IList<VendorContractStatus> ContractStatus { get; set; } } [EnforceCorrectWorkflow] public class VendorContractStatus { public virtual VendorContract VendorContract { get; set; } public virtual FileStore ExecutedDocument { get; set; } public virtual string Status { get; set; } public virtual string Reason { get; set; } public virtual string CreatedBy { get; set; } public virtual DateTime CreatedOn { get; set; } } I've omitted the filestore class, which is basically a key/value lookup to find the document based on its guid. The VendorContractStatus is mapped as a many-to-one in Nhibernate. I then use a custom validator as described here. If anything but draft is returned in the VendorContractStatus collection, no changes are allowed. Furthermore the VendorContractStatus must follow the correct workflow (you can add a rejected after a pending, but you can't add anything else to the collection if a reject or accepted exists, etc.). All sounds alright? Well a colleague has argued that we should simply add an "IsDraft" bool property to VendorContract and not accept updates if IsDraft is false. Then we should setup a method inside of VendorContractStatus for updating the status, if something gets added after a draft, it sets the IsDraft property of VendorContract to false. I do not like this as it feels like I'm dirtying up the POCOs and adding logic that should persist in the validation area, that no rules should really exist in these classes and they shouldn't be aware of their states. Any thoughts on this and what is the better practice from a DDD perspective? From my view, if in the future we want more complex rules, my way will be more maintainable over the long run. Say we have contracts over a certain amount to be approved by a manager. I would think it would be better to have a one-to-one mapping with a VendorContractApproval class, rather than adding IsApproved properties, but that's just speculation. This might be splitting hairs, but this is the first real gritty enterprise software project we've done. Any advice would be appreciated!

    Read the article

  • ASP.Net MVC 2 is it possible to get the same instance of model(with slight changes) in HttpPost meth

    - by jjjjj
    Hi I have a complex entity User: public class User : BaseEntity { public virtual Taxi Taxi { get; set; } --> That is why i call it "complex" public virtual string Login { get; set; } public virtual string Password { get; set; } } where Taxi is a parent of User (Taxi has-many Users): public class Taxi : BaseEntity { public virtual string Name { get; set; } public virtual string ClientIp { get; set; } } BaseEntity consists of public virtual int Id { get; private set; } The problem occurs while trying to edit User [Authorize] public ActionResult ChangeAccountInfo() { var user = UserRepository.GetUser(User.Identity.Name); return View(user); } My ChangeAccountInfo.aspx <fieldset> <legend>Fields</legend> <% %> <div class="editor-label"> <%: Html.LabelFor(model => model.Login) %> </div> <div class="editor-field"> <%: Html.TextBoxFor(model => model.Login) %> <%: Html.ValidationMessageFor(model => model.Login) %> </div> <div class="editor-label"> <%: Html.LabelFor(model => model.Password) %> </div> <div class="editor-field"> <%: Html.TextBoxFor(model => model.Password) %> <%: Html.ValidationMessageFor(model => model.Password) %> </div> <div class="editor-field"> <%: Html.HiddenFor(model => model.Taxi.Name)%> </div> <p> <input type="submit" value="Save" /> </p> </fieldset> Post changes: [Authorize] [HttpPost] public ActionResult ChangeAccountInfo(User model) { if (ModelState.IsValid) { UserRepository.UpdateUser(model); return RedirectToAction("ChangeAccountInfoSuccess", "Account"); } return View(model); } But, the (User model) parameter has User.Id == 0 -- User entity had 5 before edit User.Login == "my new login" User.Password == "my new password" User.Taxi.Id == 0 -- User.Taxi entity had 3 before edit User.Taxi.Name == "old hidden name" User.Taxi.ClientIp == null -- User entity had 192.168.0.1 before edit Q: Is it possible not to mark all the fields of an entity (that should be in my UpdateUser) with tag "hidden" but still have them unchanged in my HttpPost method? e.g. not User.Taxi.ClientIp = null, but User.Taxi.ClientIp = 192.168.0.1 I'm using nhibernate, if it matters.

    Read the article

  • Map GEO API Services

    - by Lee
    Does anyone know of a good even paid API for mapping to get GEO stuff. I am really frustrated with google map giving poor results even though it beats all others. I have tried so far. Google Yahoo BING Mapquest Multimap Can anyone suggest other good services ? Hope ya CAN !

    Read the article

  • design of orm tool

    - by ifree
    Hello , I want to design a orm tool for my daily work, but I'm always worry about the mapping of foreign key. Here's part of my code: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; namespace OrmTool { [AttributeUsage(AttributeTargets.Property)] public class ColumnAttribute:Attribute { public string Name { get; set; } public SqlDbType DataType { get; set; } public bool IsPk { get; set; } } [AttributeUsage(AttributeTargets.Class,AllowMultiple=false,Inherited=false)] public class TableAttribute:Attribute { public string TableName { get; set; } public string Description { get; set; } } [AttributeUsage(AttributeTargets.Property)] public class ReferencesAttribute : ColumnAttribut { public Type Host { get; set; } public string HostPkName{get;set;} } } I want to use Attribute to get the metadata of Entity ,then mapping them,but i think it's really hard to get it done; public class DbUtility { private static readonly string CONNSTR = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString; private static readonly Type TableType = typeof(TableAttribute); private static readonly Type ColumnType = typeof(ColumnAttribute); private static readonly Type ReferenceType = typeof(ReferencesAttribute); private static IList<TEntity> EntityListGenerator<TEntity>(string tableName,PropertyInfo[] props,params SqlParameter[] paras) { return null; } private static IList<TEntity> ResultList() { return null; } private static SqlCommand PrepareCommand(string sql,SqlConnection conn,params SqlParameter[] paras) { SqlCommand cmd = new SqlCommand(); cmd.CommandText = sql; cmd.Connection = conn; if (paras != null) cmd.Parameters.AddRange(paras); conn.Open(); return cmd; } } I don't know how to do the next step, if every Entity has it's own foreign key,how do I get the return result ? If the Entity like this: [Table(Name="ArtBook")] public class ArtBook{ [column(Name="id",IsPk=true,DataType=SqlDbType.Int)] public int Id{get;set;} [References(Name="ISBNId",DataType=SqlDataType.Int,Host=typeof(ISBN),HostPkName="Id")] public ISBN BookISBN{get;set;} public .....more properties. } public class ISBN{ public int Id{get;set;} public bool IsNative{get;set;} } If I read all ArtBooks from database and when I get a ReferencesAttribute how do I set the value of BookISBN?

    Read the article

  • Map denormalized hibernate

    - by Jurgen H
    I have a Summary class which contains a list of Qualities. A Quality contains a String name and int value. This data is stored in a denormalized db structure, one table only, for both Summary and Quality. Quality table: id, somefileds, qualityname1, qualityvalue1, qualityname2, qualityvalue2, qualityname3, qualityvalue3 For each quality name & value pairs, a new Quality object must be inserted in the Summary class. How to map this in hibernate (xml hibernate mapping)?

    Read the article

  • asp.net 4.0 web forms routing - default/wildcard route

    - by Martin Robins
    I there a simple way when using ASP.NET 4.0 routing with Web Forms to produce a route that will act as some kind of wildcard? It seems to me that within WebForms, you have to specify a route for every page - I am looking for some kind of generic route that can be used where nothing specific is required, perhaps mapping directly from path to path so... http://somedomain.com/folder1/folder2/page would possibly map to folder1/folder2/page.aspx Any suggestions? Thanks

    Read the article

  • How to do multiple column UniqueConstraint in hbm?

    - by DataSurfer
    Working on some legacy hibernate code. How do I do the following with hbm.xml(hibernate mapping file) instead of with annotations? @Table(name="users", uniqueConstraints = { @UniqueConstraint(columnNames={"username", "client"}), @UniqueConstraint(columnNames={"email", "client"}) }) public class User implements Serializable { private static final long serialVersionUID = 1L; @Id private int id; private String username; private String email; private Client client; }

    Read the article

  • Hibernate - get the size of a list in a property

    - by mada
    I have a class A which have a list of B elements. In my A class i would like to add: int size; which will be valued with the number of B elements. So when I would call myA.getSize() I will have it. Is it possible to map a count query with a single property in the hibernate mapping? I don't want to load the list that is why i would like to add a size property.

    Read the article

  • standard geographic tilizing/binning method?

    - by monkut
    I'm trying to learn and understand more about mapping and displaying values on a map. (GIS) At the moment I'M looking to take some values and apply those values to a tile or bin on a map. Ideally I'd like the tile sizes to be uniform, like 100 meters, 500 meters, etc. Is there a standard method for creating uniform tile sizes? Or Are what are common accepted method to deal with this kind of data display? (Currently I'm using geodjango and it's related toolset geos, proj4, etc)

    Read the article

  • Multiple INET sockets (mulple IP's too) connected to UNIX sockets

    - by Andrew
    HOST = same host all the time, accepts multiple connection. I have a dedicated server and I will buy extra IP's. Socket 1 connects to HOST:PORT, from IP-1 Socket 2 connects to HOST:PORT, from IP-1 Socket 3 connects to HOST:PORT, from IP-1 Socket 4 connects to HOST:PORT, from IP-2 Socket 5 connects to HOST:PORT, from IP-2 Socket 6 connects to HOST:PORT, from IP-2 After creating all sockets I want to access them easy as UNIX sockets from PHP. /sys/socket1 /sys/socket2 /sys/socket3 /sys/socket4 /sys/socket5 /sys/socket6 I want the sockets to work in background (like daemon) and I want to be able to connect from PHP to any of this sockets and RECV/SEND whatever I want. I saw "socat" and I think that's the solution for me, please tell me how to use socat, or how to do it other way. Thankyou!

    Read the article

  • mappoint 2013 randomly crashes on import

    - by ErocM
    We are sending routes to Mappoint 2013 from our application using an access database. It seems to happen with Mappoint 2010 and 2011 also. It doesn't happen on all of our clients either and it happens randomly on those who it does happen. This is the message: Problem signature: Problem Event Name: BEX Application Name: MapPoint.exe Application Version: 19.0.18.1100 Application Timestamp: 4fd664bb Fault Module Name: StackHash_94b0 Fault Module Version: 0.0.0.0 Fault Module Timestamp: 00000000 Exception Offset: 7f82c94f Exception Code: c0000005 Exception Data: 00000008 OS Version: 6.0.6002.2.2.0.18.10 Locale ID: 1033 Additional Information 1: 94b0 Additional Information 2: 30950b6006304277980cdff17dfbd104 Additional Information 3: 098a Additional Information 4: 31c80150ac0b74b2dcb7884aa8fa1dac Does anyone know where I'd find out more information on this or how to resolve it? If this is not the correct exchange, pls point me to the right one and I'll delete and respost it. Thanks!

    Read the article

  • how to program a special key on my laptop?

    - by daniel11
    ok so i have a set of touch screen buttons on the top of my laptop's keyboard, (one turns on power save mode, one disables/enables the mouse touch pad, one toggles the wifi adapter, and two turns the volume up/down) however theres another one that opened a file backup utility that came with my laptop. but since i bought my laptop , ive uninstalled that utility, rendering this button useless. So i was wondering if it was possible to reprogram that button to open another file or program on my computer? And if so what are the requirements and how would i go about doing it? Thanks in advance!

    Read the article

< Previous Page | 69 70 71 72 73 74 75 76 77 78 79 80  | Next Page >