The latest installment of the Summer of NHibernate screencast series is now available for download.
I will warn potential viewers in advance that this session is heavily focused on techniques and approaches that tend to contradict most Domain-Driven-Design/Development practices so please don’t waste your time telling me this — I know it already . Leveraging NHibernate to better support DDD principles is coming in the next session, I promise.
Instead, this session focuses on techniques, approaches, concerns, and implementation practices that support effectively leveraging NHibernate in situations where (for all kinds of really good requirements reasons) your database schema design occupies a position of primacy in the hierarchy of your design constraints.
In this session we dig into the use of the MyGeneration OSS code-generation toolset and understand how we can use it to completely slave our Data Transfer Objects and their related .hbm.xml mapping files to the design of our database schema, entirely freeing us from having to manually code and maintain these solution artifacts during our development process.
We also investigate techniques to avoid the inclusion of ‘string-literal’ values in our CriteriaAPI and HQL queries so that we can get complete compile-time type-checking on all of the statements in our NHibernateDataProvider class if/when things change in other layers of our application (e.g., the database schema), making reacting to change and catching errors all the more simpler for us.
There isn’t a whole lot of new NHIbernate-centric content in this screencast as its more about how to use tools and techniques to drive NHibernate in certain kinds of application design situations, but hopefully people will still find it to be of value.
As usual, comments and feedback (and criticism!) are greatly appreciated.
When updating the tests to work with the generated DataTransfer project, you mentioned that the test that tried to delete a customer, which still had foreign key references, was failing because the cascade setting in the mapping file was set to “all”, in opposed to “none”, in the generated version.
That made explanation made sense, but what I couldn’t work out from this tutorial was why the test was passing with the hand-written DataTransfer project, as you needed to correct the test to call the method for getting an *undeletable* customer.
@James:
I think that change (to get the ‘deletable customer’ was actually left in there from a refactoring that I did during a ‘dry-run’ of the screencast and then failed to properly return to ‘undeleteable customer’ before doing the recording — oops~!
I think if you go back to the code download from BEFORE this session (e.g., from session 07 or prior) you will see that the unit test that test did indeed USED TO READ ‘GetUndeletableCustoimer()’ as expected.
This is (I think) something I failed to rollback properly before beginning the recording…I wonder whether its actually worth re-recording that snippet from the session so that it doesn’t happen that way in the recording…I admit its confusing as heck since it happens right as I’m trying to explain the differences between cascade=”none” and cascade=”all”.
Thoughts…?
hi, just noticed that you used your own MyGen template to create nhib mapping files, and this template is not avaiable from MyGen repository. So I’m wondering if you’re going to make it public or is it only for your private job :). I like it very much because it’s highly customizable and powerful
@Steve:
I think your “on screen” explanation made sense, even at 1.5x, but it would have probably been a little clearer without that issue – I did notice you pause just as you started looking at that test, which made me wonder if you noticed it straight away, but you seemed surprised by it later on, so maybe not…
Anyway, personally, I didn’t mind, it just left me wondering why it passed previously, hence the earlier comment, but now that you’ve cleared that up, I’ll be able to sleep tonight! 🙂
@Libor:
Its in the root of the \DataTransfer folder in the solution from the code download that accompanies this session on the SummerOfNHibernate.com site.
Its uncompiled text; enjoy 🙂
I found a sample on “MSDN Code” a small application with NHbiernate.
Here you are : http://code.msdn.microsoft.com/NHibernateAccessExte
When I ran MyGeneration against my database, it picked up everything except the View that I created. In fact, the View tab was missing from the resulting Template dialog box. I checked permissions on the View and it should be publicly accessible. What am I doing wrong?
Ignore my previous question, apparently I was connecting to an older version of the database.
Hello
first off all, many, many thanks for this great Screencast series! But now i have a question. I need to create a many to zero / one to many relation between a table and a view. (Table is one view is many) Is there a chance to use your great MyGen template for this?
My Problem is i have the following structure:
Adress –> contacts –> communication (emails,telefonenumbers etc)
|—————->
create table adress
id primary key
name …..
create table contacts
id primary key
adressid fk to adress
type …..
create table communication
id primary key
adressid fk to adress
contactsid (if 0 then belongs to adress, else belongs to contacts)
Now my idea was creating two views
1. create view from table communication WHERE contactsid=0 (all communications from adress)
2. create view from table communiction WHERE contactsid0 (all communications from contacts)
and with that views create many to zero and one to many relations in nhibernate? Or must i change the DB Strucure to create two tables for communication?
Sorry for the very long post!!
Michael
@Michael:
The MyGen template itself definitely will NOT support what you are suggesting here (constructing DTO class and accompanying mapping file that is a combination of a table and a view). The mapping file is designed to support only really one ‘model’ of DTO/mapping in NHib, that which is usually referred to as ‘table-per-concrete-class’.
You MAY be able to accomplish what you are after by hand-writing the mapping file(s). Though I have never attempted exactly what you are after here, I suspect that it might be possible using the joined-subclass attribute approach (google on this term and you will find examples).
You would have to be careful to ensure that either the props on your classes that point to these views were read-only or that the view was updateable (per whatever rules apply for your DB that would allow updateable views) else I think when you would persist these objects back to the DB you would get errors when NHib tried to push values back into the view-based props that weren’t properly updateable.
Doing this would sort of mean that you would lose your DB-neutrality with NHib since not all underlying DB targets support updateable views, of course. Not DONT DO THIS, but DO THIS AWARE OF THE CHOICES YOU ARE MAKING.
Hope this helps~!
@sbohlen:
Thanks for your quick reply. I think i must change my table structure a little bit. I will do it the other way around ;-). I will create two tables for communiction, one for the adress and one for contacts! For the older Software, that is using this combined table just for selects not for updates, i will create a view that unions table A and table B. And voila everything works for me ;-).
But now i have a new, smaller problem. Im a using Firebird as DB. In the table Adress there is a Textblob. Unfortunately your template translates this into string lenght=0! Can i change this behavior? If not I must change the entity and the mapping files each time i create them.
Michael
@Michael:
Frankly I never tested the template against Firebird as we have never used that database (sticking mostly to MSSQL and Oracle), but I strongly suspect that this ISN’T per-se an issue with the template itself. The template is just responding to what the MyGeneration ‘mymeta’ library has ‘discovered’ about the target DB schema and ‘reported’ back to the template.
If the field length for a CLOB field under firebird is coming back 0 then I strongly suspect that this is actually a shortcoming of the MyGeneration DB-schema interrogator (MyMeta) rather than the template itself since the template doesn’t actully ‘know’ about field lengths other than from what MyGeneration ‘tells’ it via the MyMeta library.
Some thoughts about how to better isolate this:
1) try the template against another DB target and see what you get for the length of a CLOB field there (e.g., MSSQL, Oracle, or even MySQL if you want a free test target)
2) In MyGeneration there is actually a ‘MyMeta Browser’ pane you can open and use to navigate the schema of your DB ‘as viewed by MyGeneration’. If that’s reporting 0 then the issue isn’t with the template. If that’s reporting 5000, 8000, VARMAXBINARY, VARCHARMAX, or whatever the ‘right’ answer is for Fiebird, then the fault has to lie in the template somehow
Let me know if you can isolate it. If the issue is with MyGeneration/MyMeta then you will have to either report it as bug via its sourceforge site, grab the code and fix it yourself (since its OSS), or just live with it 🙂
If the issue can be found to be with the temp[late, let me know that too and I will update the template to correct this and make it available for download from here as a bug-fix to the template itself.
Either way, just let me know.
@sbohlen
Seems to be a Bug in MyGeneration/MyMeta. BLOB(Text) is always returning 0 for CharacterMaxLength. Maybe i try to change your template to avoid this if DataTypeName is BLOB(TEXT). But now i go on vaction for the next 14 Days. Thanks again for your help!
Michael
@Michael:
Makes me feel better (sort of!). Glad you isolated it but I would request that you log it as a bug for the MyGeneration team (on sourceforge) to address so that they can get it fixed and re-released accordingly.
Enjoy your vacation 🙂
Steve,
i’m not sure if you forgot to talk about IsDeleted and IsChanged or you planning to talk in the next session? 🙂
thanks for your time.
@Nisar:
isDeleted and isChanged (in the context of these templates) are only provided for ‘convenience’ use of consumers of the classes for when they are used in a detached condition (e.g., the session that retrieved them is no longer in scope). If the persisted objects DO have a session, then asking the session about them is the best way to determine their peristence state.
In an upcoming installment (though not the next one) on managing session lifecycle for web apps and windows apps I will talk a bit about the idea of detached entities and how we deal with them and this will make some of this more clear.
Thanks Steve i will be waiting for your next video 🙂
Steve,
I had heard about MyGeneration but never used it before, so it was really cool to see it in action.
I tried to take your template and set up a build step that would re-gen the output classes using the zeuscmd utility. However, it blows up trying to serialize the XML document that contains all of the parameters from the interface when I run it with the -c switch. I believe that I can get around that one way or another but was wondering if you had any suggestions.
Also, the template uses the preprocessor variable OVER_VISUAL, which looks (and sounds) like it is supposed to help with running the template with zeuscmd but I haven’t been able to figure out how to define OVER_VISUAL; the script processor complains no matter where I put the #define. I’m still digging for that answer, but again was wondering if you would point me in the right direction.
Great series! And Thanks…
Steve:
Great series! This has helped crystalize alot of the nHibernate documentation that I was trying to wade through. Quick question: I haven’t seen any references yet to handling class inheritance in the database to object mapping. If I missed it, could you point me to session where this was covered or is this on the agenda for Session 09?
Thanks for all of your hard work! This has been fantastic and extremely helpful!
@Ray (Megal):
That issue (lack of coherent support for the zeruscmd.exe command-line instance of MyGeneration) is something that was there in the base template from which we extended our own (that’s included in the download). I too was never able to get around the XML serialziation limitations that you are describing but likes the template enough to use it as a basis for ours anyway.
I always meant to (some day) dig into the details of exactly what was going on there to produce that error but never had the spare cycles to look into it — which is unfortunate as I tend to like the scriptability that the zeuscmd approach gives me.
If you DO manage to find the time to resolve this, would you do me a favor as pass your updates back to me — I would certainly like that issue fixed and I have to imagine that others that downloaded the code samples from that session would as well.
Thanks and let me know what you uncover in your investigation.
@Ray:
Class inheritance is planned to be addressed in a later session 10, 11, 12 — not entirely certain at this point. Originally I had skipped it entirely as it wasn’t considered (by myself) to be an NHib ‘foundational’ concept but was rather considered by myself to be an advanced topic outside the scope of this series (I’m NOT trying to teach EVERYTHING about Nhib, but focusing on the basic fundamentals here).
However, I have reconsidered this and am now planning to cover the other methods of modeling objects in the database in addition the table-per-concrete-class style that we have implemented thus-far in the sessions. I expect that I will likely have an upcoming session that covers both table-per-subclass and table-per-joined-subclass models of class-to-db mapping as well.
Patience; all will come in due-time 🙂
I am glad that you’re finding value in the content; hope its helping to spur your adoption of the technology.
I’ve been trying out the Microdesk MyGeneration template using the AdventureWorks database. The code that gets generated (with the same MyGeneration settings as was used in this session (8)) have two problems.
1. If a table has a non-composite primary key AND the primary key is also a foreign key AND “Apply Pascal case” is checked, the type of the primary key in the class i capitalized. This means that “int” becomes “Int”, which will not compile. If “Apply Pascal case” is unchecked, it works. Note that this is a problem also for the template on which the Microdesk template is based.
2. The properties “IsDeleted” and “IsChanged” are not marked virtual. That generated the following error when running the tests. “The following types may not be used as proxies : ScrapReason : method get_IsChanged should be virtual”. If I mark them as virtual, it works.
Now, I’m pretty sure that number 1 is an error. However, number 2 I’m a little unsure of. I see that in lesson 8, the methods are not marked virtual, and it seems to work. The adventureworks database is definitely more complicated than the database used in lesson 8, so that could be the reason for the difference.
Thanks!
@tab:
Thanks for the feedback. For number 2, really ALL methods is just about any code-gen-ed class should really be marked virutal to allow max flexibiloyt in overriding outputted behavior without having to edit the code by hand post-generation so I will mod the template per that suggestion.
For number 1, this is definitely a bug (and also definitely something that is a hold-over from the template upon which ours is heavily based) but I will look into fixing it and posting an update when completed — it would be nice for everyone to get this when fixed, of course.
Thanks for the feedback~!
-Steve B.
@Steve,
thanks for your response above. I have two more issues I would like to mention. Again, I’m using the AdventureWorks database.
1. In AW, the tables are put into Schemas (other than dbo), and when referencing a table, the schema must be included, or an error will occur. “Select * from Product” will not work, but “Select * from Production.Product” works. Now, I thought that the “DB objects prefix” was intended for this purpose. Whether this is the intended purpose or not, I dont know, but I know that it doesnt work. From session 8, I got the impression that this was how that parameter was supposed to work. What I would like is another checkbox parameter “Include schema in table name” (or something like that). When checked, the tablename in the mapping file would be prefixed with the Schema.
2. Now, when I manually correct this in the mapping file another problem arises. If I use for example `Production`.`Product` as tablename, NHibernate is not able to resolve it. It claims that it cannot find ‘Production`.`Product’. Now, if I manually change the tablename in the mapping file to [Production].[Product], everything works fine.
I guess the first problem could be resolved in the MyGeneration template. I looked in the template code, and could see that the schema was not prepended to the table. However, I was not able to figure out how to do this. The second problem seems to be an NHibernate problem, or??
Any thoughts on these issues?
I’m using NH 2.0 CR2.
Thanks!
@tab:
#1 seems like another issue with the template — again, that part of the template wasn’t something that we modified ourselves but I will take it under advisement since its clearly something that we need to FIX in the template if/when we use it ourselves in conditions such as you are decribing here. No timeline commitment for my fixing it, but I will definitetly put it into the hopper (backlog) for me to address.
Re: #2, I cannot speak to whether this is an issue with NH 2.0 vs working fine in NH 1.2 as I have to-date written exactly ZERO lines of code against NH 2.0 although I have followed its change-log to keep abreast of what’s going on there. I DO have a theory however….
You indicate that [Production].[Product] works fine whereas `Production`.`Product` fails. If you use [Production].[Product] then NH won’t really do anything special with these values since its just using whatver you type there *literally* (e.g., its sending the whole string to the SQL server as-is) and since [ ] represent perfectly legal chars in MSSQLServer, this works fine. This is, of course, a DB-specific escape sequence and won’t work for other platforms.
I suspect strongly that if you try Production.`Product` even in NH 2.0, this will likely work fine (e.g., the NH-expected back-tick (`) is permitted around the TABLE name but not the SCHEMA name). This MAY or MAY NOT be a bug in NH (1.2 -or- 2.0) as its not clear to me that its actually permitted in the DB to have a schema name that is itself a ‘reserved word’.
I’ve never tried this, but do you happen to know if its possible (in SQLServer or any other db platform) to have a schema.table name of [Order].[Group] (for example) where both the schema AND the table are reserved words? Or is only the table permitted to be a reserved word? This might explain why NH (1.2 -or- 2.0) doesn’t accept the back-tick escape char around the schema part of the fully-qualified schema.table construct.
Thoughts?
@Steve,
I was able to adjust the template so that Schema is included in the mapping file. However, I had to revert to using [] instead of back-ticks. It seems NH have got som issues in this matter. I created a Schema named Order and in this schema I created a table called Order. This means that the table attrib in the mapping file should be [Order].[Order]. No matter what else I tried to enclose the Schema/Table in, it would not work. I tried `Order`.`Order`, Order.`Order`, [Order].`Order`, but it would not work.
Since I use SQL Server 2005, I will use the proprietary [], but I guess somebody should look closer at this and see whether it is real problem, or if I’m doing something wrong. Also note that I tried this with both NH 2.0 CR2 and NH 1.2.1
@tab:
If you have modified the template, can you return your edits back to me so that I can incorporate them back into our instance and make available to others?
re: the nhib issue on escaping schema strings, I will post this as a bug for the NH team to look into; I’m sure they can address it (tho probably not until 2.1.0 as I understand 2.0 is going to RTM (does an OSS project actually RTM?????) on Monday next and its certainly too late to get this into the 2.0 release code at this point.
Hi Steve,
i try to use the MYGeneration tool with NHibernate template which you provided in the project and when i try to generate mapping/dto classes i get the “unknown” type.. what i’m missing?
please see below
Unknown VisitInfoId
{
get ;
set ;
}
Unknown VisitInfoNm
{
get ;
set ;
}
thanks.
@Nisar:
Can you advise what database you are targeting? This would seem to be the result of MyGeneration not being able to correctly determine the data type of the field in the database.
One way to test this (independently of the actual template code) is to use the MyMeta Browser in MyGeneration to navigate to the table in the DB that contains these fields and see what it reports. MyMeta is the library that MyGeneration uses to interrogate the DB schema so if the MyMeta browser reports correct type then the issue is with the my template but if MyMeta doesn’t return the correct type then the problem is in MyMeta instead of the template.
Let me know what you find out.
-Steve B.
i’m using ms-sql server 2005
I browse to MyMeta Browser and select the database>>select my table which i’m working on and click on “MyMeta Browser properties” and seems everything is okay except that
LanguageType = Unknown
DbTargetType = Unknown
http://www.freeimagehosting.net/image.php?5825605481.jpg
also please see the url i have attached the print screen to get a good picture of whats going on.
thanks
also one more quick question:
thou i’m connecting to ms-sql server but do i still need to a provider = “SQLOLEDB” ? should be sql only ? (if i provide only SQL in the provider it fails to connect)
the below connection string works fine:
Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=MyTest;Data Source=SQL-DEV
the below connection failed: (note: i just have provider=SQL)…
Provider=SQL.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=MyTest;Data Source=SQL-DEV
i’m thinking that may be the reason why my
LanguageType = Unknown
DbTargetType = Unknown
??
just thinking loud 🙂
@Nisar:
Sounds like you are having some issues with MyGeneration here. Some thoughts…
1) MyGeneration uses the MSSQLOLEDB driver to communicate with MSSQL server internally, so that (by itself) isn’t your issue.
2) On the [Connection] tab of the Edit Menu –> Default Settings dialog there are selectors for your choice of language and DB target. You MUST select a value for each of these else MyGeneration won’t know how to process what it finds in your database. If you don’t have values in the combo boxes to select from, you need to properly point MyGeneration to the XML files that contain these choices. If you accepted the default installation location, then these files should be C:\Program Files\MyGeneration13\Settings\Languages.xml and C:\Program Files\MyGeneration13\Settings\DbTargets.xml If you don’t have these files somewhere, then you need to reinstall MyGeneration since you are missing some of the required files.
Hope this helps.
i uninstalled mygeneration and seems that the problem is fixed….
but now i’m having a different error now, i have around 200 tables and it able to create some of the mapping files not all and does not create any dto classes and below is the error message
8/29/2008 3:14:07 PM – Executing: Microdesk NHibernate Template 1.1
8/29/2008 3:18:56 PM – ERROR: [Zeus.ErrorHandling.ZeusRuntimeException] – Template Runtime Exception
8/29/2008 3:18:56 PM – Canceled Template execution: Microdesk NHibernate Template 1.1
8/29/2008 3:18:56 PM –
8/29/2008 3:18:56 PM – Completed
is this because i have too many tables?
@Nisar:
Interesting; I’m not certain the cause but since you CAN choose how many of the tables you want to generate classes + mapping for, perhaps try a smaller number of tables and see if you get better results…?
I am unaware of any specific limitation on the number of tables. Obvioulsy there isn’t a .NET datatype that I would have used in the template code that would have been limited to 200 — or even the more often boundary of 256 — so I don’t think this is an issue w/the template code. I don’t think I’ve every tried the template on that many tables at once so I cannot report one way or the other.
Perhaps its a limitation of MyGeneration, but you can maybe isolate this by running some other template against all those same tables — even if you don’t care about the output from any other template, you could gauge MyGeneration’s success/failure at running some other template against your same DB to see if the issue is w/the template or MyGeneration. ZeusRuntimeException sure sounds like its MyGeneration, but it may be an error in the template that’s triggering this exception too.
thanks Steve… is there a way MyGeneration tool allows you to select specific tables? i could not figured out how would i do.
@sbohlen
Hello,
i am back from vacation. I figured out that the Problem with BLOBs in Firebird and your Template is a Problem with the Firebirdprovider for MyGen. I just send a Mail to the Developer, maybe he can help.
But now i have another Problem. I use the release Version of Nhibernate and i had to change your template to create the clone method and the isDeleted/isChanged properties as virtual, because the Release Version of Nhibernate requires it. Maybe you want to change it in the Download?
Michael
@Micheal:
Welcome back; I hope you went somewhere nice 🙂
Re: the template, the virtual issue as well as another was identified by another viewer and I am planning this weekend to merge all the submitted changes back into a new one that I plan to make avail for download after that. That’s what I get for releasing a semi-tested beta template 🙂
@sbohlen
Hello,
great news. As I said in my last post, I am in contact with a developer (Justin Greenwood) of MyGeneration. He changed the Firebird Provider for MyGeneration to support:
– ForeignKeys
– BLOBs
– AutoKeys (Generators in the FB World or Identity Fields on MSSQL)
– fixed some other Bugs
Great work Justin!
Michael
Me again,
Justin Greenwood had done a lot of work to get MyGeneration work together with Firebird/NHibernation). The last thing he does, was an enhancement for AutoKeys in Firebird. Your Template is generating the following .hbm code if it finds and isAutoKey for a column:
For MSSQL this seems to be right ;-). But not so for Firebird. According to the documentation for Hibernate found here: http://www.hibernate.org/hib_docs/reference/en/html/mapping.html#mapping-declaration-id-generator it should be:
GEN_ID
For Firebird and maybe PostgreSQL too, nhibernate needs the Name of the Sequence/Generator to get the AutoKey. Justin channged the Firebird Provider to achieve this. You can get the Name from:
string genName = (string)column.DatabaseSpecificMetaData(“GeneratorName”);
The property DatabaseSpecificMetaData is used for such things ( also in MSSQL ). Now I have changed you Template a little bit ;-):
From
if(!isComposite )
hbm.AddAtt(
hbm.AddValue(ni, “generator”), “class”, c.IsAutoKey ? “native” : “assigned”);
To:
if(!isComposite ){
if (!c.IsAutoKey){
hbm.AddAtt(hbm.AddValue(ni, “generator”), “class”, “assigned”);
} else {
string genName = (string)c.DatabaseSpecificMetaData(“GeneratorName”);
if (genName != “”) {
XmlNode generator = hbm.AddValue(ni, “generator”);
XmlNode prop = hbm.AddValue(generator, “param”);
prop.InnerText = genName;
hbm.AddAtt(prop, “name”, “sequence”);
hbm.AddAtt(generator, “class”, “sequence”);
} else {
hbm.AddAtt(hbm.AddValue(ni, “generator”), “class”, “native”);
}
}
}
With this change Autokeys are working for MSSQL and Firebird!
Greetings
Michael
@sbohlen
Hello,
do you plan to implement the IEditableObject in your Template? Something like that:
http://forum.hibernate.org/viewtopic.php?p=2377698&sid=778ac3098411968c4915f8acaa4b77a7#2377698 ?
Michael
@Michael:
This is great news (firebird support improving in mygeneration); I am in the process right now of folding some other modifications into our template and will add this one as well before I plan to re-release it for all interested parties.
Also, in re: IEditableObject, I think that this will become an option in the template from which a user can select to opt-into or not when generating the classes from the template.
.NET (2.0) provides actually several interfaces (of course) that all actually play a role in the larger .net databinding infrastructure, and IEditableObject is actually one of the more obscure interfaces, its only raison-d’etre is actually so that classes that implement it can participate fully in being bound to a datagrid control and support in-place editing, etc. of all things (a somewhat obscure reason for the introduction of an interface, but hey — I’m not on the .NET fx team, so who am I to complain???)
The other Internfaces that need to be implemented are INotifyPropertyChanged (for each object) and IBindableList (often implemented via the “I am a lazy guy” helper class of BindingList<T>) for collections. Its certainly true that IEditableObject is useful for NHibernate users to interrogate the object directtly to determine dirty, etc. state, but it seems to me that if I am to bother to implement IEditableObject, then I should take the time to also do the work for the rest of the databinding Interfaces as well 🙂
This may not happen for a few weeks as I’m a bit backed up with other committments (including other non-business coding efforts that I’ve committed to) but look for it sometime mid-October, I would guess.
@sbohlen
I am on my way to port a project to nhibernate and .NET. And for that I needed the IEditableObject. And I managed it to implement this Interface in your template;-). If you would like to have my changes, then please email me. Maybe I will include the INotifyPropertyChanged in the next of days. The next thing I want to implement is the possibilty to enter a comma separated list of files (*.hbm and *.cs) that should be included in the Projectfile to give the user the possibilty to write e.g. Named SQLs and include them into the ‘DataTransfer’ part. Are you interested?
Michael
Hi Steve,
I wonder if you can help with connecting MyGeneration to a SQL Express database file that I have within my VS2008 project.
I am trying the following: Provider=SQLNCLI.1;Server=.\SQLEXPRESS;AttachDbFilename=C:\Users\Simon\Documents\Visual Studio 2008\Projects\OrtwinThyssenJewellery\src\app\OTJ.Program\OTJDB.mdf; Database=OTJDB; Trusted_Connection=Yes;
but that throws back an error “Directory lookup for the file [filename] failed with the operating system error 5(error not found).
I can connect if I move the mdf file to the data folder for SQL Server, so its not a problem with the files.
@Simon:
Interesting; I don’t know that I (personally) have any actual experience trying to use MyGeneration to connect to a .mdf file NOT via the SQLServer (express or std/enterprise) file-system-path driver.
Maybe check with the MyGeneration support forums to see if others have a solution for you –? Also, perhaps ensure that you are using the latest MyGeneration release too…?
Sorry cannot be of more help, but I am a (bigger) believer in actually ‘mounting’ the database into the database server itself rather than relying on the file-path-based connection you are attempting here.
Wouldn’t mind finding out how you (if you are able) eventually get this to work, so would appreciate a post about your resolution if/when you get it working.
Hi Steve,
Mounting the database is my usual approach, but in this case I needed to deploy the application stand-alone – the file path approach seemed to be a good approach and I have had no problems using it. The set up deploys the mdf (an embedded resource) to a configurable folder and the connection string is set to that address.
Anyways… I had a bit more of a play with MyGeneration (there was nothing helpful in the forums or documentation), (I’m on 1.3.0.3) and struggled with the OLEDB button settings; I don’t write connection strings by hand any more so much of this had gone out of my head. But using OLEDB, setting the Data Source to .\SQLExpress and entering the location for my database I have made a successful connection to the mdf file; here’s the connection string, hope someone finds it helpful:
Provider=ADsDSOObject;Encrypt Password=False;Integrated Security=SSPI;Data Source=.\SQLExpress;Location=C:\Users\Simon\Documents\Visual Studio 2008\Projects\OrtwinThyssenJewellery\src\app\OTJ.Program\OTJDB.mdf;Mode=Read;Bind Flags=0;ADSI Flag=-2147483648
For anyone who’s interested I have posted up a quick step-by-step on how I configured MyGeneration for this scenario at http://www.sjmdev.com/post/2008/12/01/Configuring-MyGeneration-to-work-with-SQL-Express-file.aspx
Steve,
Just found this blog. Great resource, but I’m having a little trouble adapting this lesson to my own needs. I have a ManyToMany relational table in my database (SQL Server 2008) but MyGeneration doesn’t seem to be picking it up as such. If I exclude it from the mapping manually, Visual Studio chokes on the build because the two Classes (tables) that are joined through that foreign table are expecting there to be a namespace for it.
The foreign table has only two columns, each are set as foreign keys from their respective sources. The proper foreign key relationships are defined in the DB. Not sure what else I’m missing. Any insight would be appreciated.
Thanks.
@Dave:
Without the DB or more details its hard to know for certain, but my several ideas go like this:
* SQL Server 2008 introduced (finally!) correct support for schemas in SQL Server; its entirely likely that the MyGeneration template doesn’t take that into consideration since they were built for SQL 2005 where schema support was more…lets’ say “inconsistent”
* ensure all your tables are in the same schema and see if that helps
* try to revert your DB to SQL server 2005 and see if that helps
Failing any of that, if you want to send me a SQL script from which I can construct your DB along with the MyGeneration template you are using, I’d be glad to put it on my list of things to look into when I get a moment to breath (no promises when that will be).
HTH,
-Steve B.
Hi Steve
My company is just starting out with NHibernate and I’d like to thank you for your screencast series, which I have found invaluable in getting up to speed.
I just wanted to ask about the MyGeneration template you included in the source code.
My company has decided to go with the latest version of NHibernate, which left as is does not work with the MyGen template provided. Primarily my problems were with the IsDeleted, IsChanges and Clone methods not being virtual. This was easy enough to fix by editing the template.
My concern is that I’ll further along in the development cycle and discover more problems which are not so easy to fix.
I was wondering whether you had an updated version of the template that is NH 2 compatible, or if you knew of one out there?
Richard
@Richard Egginton:
I’m glad you were able to find value in the screencast series; thanks for the feedback!
We don’t really use the template-driven code-gen-the-DTO approach much any more so I have to confess to not having kept the templates up-to-date as NHibernate has moved forward into other capabilities and made minor changes that may invalidate the MyGeneration template(s) that were demonstrated in the screencasts.
That said, I know that a lot of the viewers of the screencasts DID continue to use the template-based code-gen approach and to my knowledge the change you mention that declares ALL of the public surface area of the class as ‘virtual’ is the only change that was required to adapt the template for NH 2.x. Given this, I frankly think you’re safe in proceeding to use that approach with your application.
For some background on how my views on template-driven code-gen have changed, see this post…
http://unhandled-exceptions.com/blog/index.php/2008/10/04/the-four-stages-of-object-relational-mapping-a-progression/
All that said, if you are practicing DB-first development (either because you have a legacy database to support or because that’s the level of complexity appropriate for your solution), the template-based DTO-gen approach has worked just fine for me on many applications in the past with great success so I wouldn’t worry about proceeding in that direction if its a good fit for your project.
Best of luck~!
-Steve B.