Introduction

 Top Next

Having been through a LARGE part of Julia's fine book "Programming Entity Framework (Second Edition)"

I think I now ought to start with this quote from Don Box, as I believe it to be true :-

[ .. most of us have been reading his books for years, even without realising it .. ]

=======================================================================================================================

Going about this Right ! :

Let us get a few things straight from the 'off'.

I followed through a lot of Julia's book (I am following the eBook on screen, but also have the paper copy as well)

and I suggest you acquire a copy of the 'second edition' as soon as possible (ASAP).

There are sections in her book which you will need to read yourself, but the Visual Studio parts I re-do in my words

and screen capture graphics, as I go along. We can have many more graphics in 'ClickSatrt' than Julia can in her

book - but she has a lot of useful and good things to say!

Also Julia did not have EF 4.3, as well as VS11. She probably started with VS 2008 before she moved over to VS 2010.

A few things have changed, and in particular the graphical 'Designer Surface' and its improved functionalities. I suggest

you follow me on this one, as I am just the standard developer guy, much closer to yourself than the data expert Julia.

I have used graphical designers for years, and like them a lot, AND, have had good success with them too.

Making it Easier for Yourself :

Take the advice offered in Julia's book, and in these eNotes - they have been well researched, and are based on 'good stuff' !

All too often I read postings in the News Groups form guys with lots of previous experience - BUT - when they come to new

topics as novices, they try to 'force' their way through things, instead of standing back and asking for advice. Their 'tack'

is often .... "how do I do 'this' with the new stuff ?" ........ instead of .... "how should I be going about this new stuff?".

There is a big difference, the former suggests they know point A and point B, the later that they may know 'B' but have

no idea where to start, what to use, or how to approach the new 'stuff' at all.

Well, Entity Framework is one of those topics where you should 'stand back' and listen first, and then go about things in

the way you have been pointed. Do NOT try and do it your own way ;-)

Looking elsewhere for more information :

Although these eNotes try to cover a big enough topic, there is one aspect of EF4 which needs you to go and look at

supporting information.

Once you have a 'Model' you will need to query it using LINQ, and this is where you need extra input from other sources.

When I started to write 'ClickStartLINQ' I bought two or three other text books on LINQ alone. And although we have

some useful sections here in 'ClickStartEF4' we have not enough space to do justice to LINQ querying, and Julia says

something similar in her book.

There are web links to useful samples, but I suggest you lookup 'ClickStart' to get an overview of what LINQ is about.

I know the confusion with LINQ, I spent about three weeks dealing with the details before I 'saw the light', and could

see a top down approach to learning LINQ. Its all a lot easier if you approach it from the correct angle / direction.

Below is some good advice (two bits) from Julia's book - take it on board !!

ADO.NET :

DataSets and DataReaders are not going away.

All of your existing investment will continue to function and you can continue to use this methodology

of retrieving data and interacting with it.

The Entity Framework provides a completely different way to retrieve and work with data.

You would not integrate the two technologies :-

for example, using the Entity Framework to query some data, and then pushing it into a DataSet;

there would be no point.

You should use one or the other.

As you learn about the Entity Framework, you will find that it provides a very different paradigm for accessing data.

You may find that the Entity Framework fits for some projects, but not others, where you may want to stick with DataSets.

Additionally, ADO.NET’s 'SqlBulkCopy' requires a DataReader or DataSet to stream data into the database; therefore,

you cannot do client-side bulk loading with the Entity Framework.

===============================================================

[ *** Personally, as a standard developer guy I would go further than this and say from now on, probably years after she

wrote the above for her book, you grasp EF4 in both hands and go with it 100%.

I think it has a LOT to offer and should remove a lot of tedious tasks, as well as get important details correct for us.

Here is our chance to work with custom objects all of the time we are writing code - enjoy the opportunity ;-0)

Once I used to work with ADO.NET stuff 100% of the time, albeit if I had a 'helper' class and had wrapped up some

basic ADO.NET stuff.

Now with the EF4 approach all the ADO.NET stuff is hidden all of the time, and I have to say I like the idea. *** ]

LINQ to SQL :

LINQ to SQL and the Entity Framework look similar on the surface.

They both provide LINQ querying against a database using a data model.

A frequently asked question is: why did Microsoft create two similar technologies?

LINQ to SQL evolved from the LINQ project, which came out of team working with language development.

The Entity Framework was a project of the Data Programmability team and was focused on the 'Entity SQL' language.

By the time each technology had come along far enough that it was being shown to other teams at Microsoft, it was

clear that Microsoft had two great new technologies that could target different scenarios.

The Entity Framework team adapted LINQ to work with entities, which confused developers even more because

LINQ to Entities and LINQ to SQL look so much alike.

However, they will continue to maintain and tweak LINQ to SQL.

This is not a happy situation for many developers who have made an investment in LINQ to SQL.

Microsoft is committed to maintaining LINQ to SQL in ADO.NET and has made no statements regarding deprecating it.

It has also promised to provide a migration path from LINQ to SQL to the Entity Framework and will recommend the

Entity Framework over LINQ to SQL in future programmer guidelines.

======================================================================================

[ *** There is the first piece of GOOD advice to us all. LINQ to SQL is dead, long live 'LINQ to Entities'. In fact the LINQ

part of this is NOT the issue, as the syntax of the query expression is similar, it is where the collection object comes

from that matters.

So basically, if we use the EF4 approach generally, then the querying we do is 'LINQ to Entities' and no 'LINQ to SQL'

should be used - at all.

Again, we are returning to this aspect of EF4 and that is, do it only one way, the EF4 way, and LINQ to SQL involves

other stuff we should keep clear of. *** ]

LINQ Syntax and Understanding SQL :

One thing that puzzles me about some of my colleagues, is that they think they can miss out on, or run away from,

the need to understand SQL querying, and all things SQL.

Having just done an intense seven days with EF4, and this on the back of my years working with T-SQL and Microsoft's

'Reporting Services', I think LINQ query expressions have a LOT to do with my SQL experience, indeed.

The more you know and understand about SQL query statements, the easier it will be to get good at LINQ syntax.

I suggest you try to work on improving your querying knowledge and experience so that you can do complex stuff

within the query, and not always reach for a .NET code way to do things.

You still have a powerful and flexible Server to do a lot of the data search and selection work for you, before any data

even gets sent back to your application - so use it to good effect.

Make sure you follow through the eNotes for 'ClickStartLINQ'.

'Mapping' - it won't Go Away :

Okay then guys, another misunderstood idea - mapping our data in the back-end data source to our in-memory objects.

However, which way we tackle our coding approach this task needs to be done, and done well and accurately.

There is no tool at all which can 'do the human' bit, so we are stuck with it. However, having said that, we can have

better tools to help us do the 'mapping' table columns (or fields) to custom object properties.

Having attempted to improve the ADO.NET mapping within my STATIC 'SQL-my_funcs' class in Vulcan, I think the VS11

tools and EF4 have made it about as good as it can get, without asking another experienced guys to do the task for you ;-)

Time to move on and do some learning ................

PHH - 31st. August 2012.


Modern 'Object Programming'

 Top Previous Next

Okay, some of you will say that developers have been using 'Objects' for ages, years and years.

However, the reality is probably more like many developers have been using computer languages

with 'Object' facilities for years.

Writing code with syntax based on objects is not the same as 'Object Programming', as many of

us knows.

There are many of our colleagues 'out there' who think they are good citizens of the 'OP' world,

(Object Programming) and yet they will not give up their arrays, multidimensional arrays, and

UI drop lists of strings, the list goes on and on.

Some of these same people will happily make a business object (BO) however, and know about the

benefits of using custom objects (CO) and BOs with business logic.

A few years back, well over five, Microsoft came up with WPF as a new GUI, their new Windows GUI,

and this made working with objects right up to the UI a dream. Data binding of objects to the UI is now

VERY easy, and has improved one end of our 'business application' (BA) solutions.

The problem when it comes to wishing to use an 'objective' approach throughout our BA code is at the

data end of things. So its the data end which needs to be vastly improved as far as our BA solutions

are concerned.

Most of us see the sense in working in code with 'Customer', 'Order' and 'Stock' type objects right form

the very start of things - BUT - our data, which is required in many business related solutions, is not

held in conventional 'objects', objects which are our BOs and COs.

In even the most modern SQL Server installation we see Tables, Rows, and Columns. So a BO like

'Customer' is actually held as a row, or record, in one or more tables, and even the rows are really a

large handful of separate data items.

Quite often we may have one BO held in different Tables within the database (DB). So a 'ContactPerson'

BO may have the addresses data stored in another, and quite separate, table to where the other 'Contact'

details are held.

On top of this the ADO.NET approach has been to work with Tables, Rows and Columns, and for many of us

who have used it successfully, it does feel old fashioned, and to be kindest, just a touch out of date !

I have to be honest, I came to SQL Server late, and so by the time I did I thought Data Readers felt 'old hat'.

I liked the way I could get a whole DataTable (object) back from a query, and then in one line display it

on the UI within a 'DataGrid' in WPF. This also fitted the 'disconnected model' MS were encouraging us to use.

BUT, even this is not good enough, DataTables belong to .NET 2.0 and probably earlier, they may also be

objects to you and me - BUT - are not the BO's and CO's I wish to be dealing within my business code.

In the past we have had to turn our tables and rows into our own BO's and that was a tedious business,

to say the least. Spoilt the fun of programming :(

Also we needed to turn new and changed BO's back into rows and columns in order to save the modified

data back to the persistent back-end store. Once again a tedious coding exercise.

So Microsoft have tried to address this problem / issue by providing us with features and facilities which mask

the tedium of the transfer of data to and from the back-end SQL store. Yes, it is still there - as it always was -

the relational DB is still a powerful and functioning 'beast', but we can now work in BO's and CO's over a much

wider scope of our program solution.

EF4 encompasses, or encapsulates, some of these very objective requirements, but no doubt things will get

even better.

Chapter 0 - entitled "Out with the Old, in with the New" - deals with this real and mental shift in looking at

data and our business logic and solutions for our customers.

So if we are to no longer think in terms of Rows and Columns in our business logic sections, what has

replaced these ? Well, quite simply 'Collections' of the very objects we like so much.

So in place of Tables of Rows, we have Collections of BOs., and we can enumerate over our collections.

Modern .NET collection classes are designed for what we require, as well as for data binding with WPF

as well.

I suggest we leave this introductory discussion at this point, and develop it further in 'Chapter 0'.

The title 'Chapter 0' is for Don Caton ;-) Zero based indexing is a gift from God it would appear to me!

Time to move on ..............

PHH - 26th. August 2012.


Software platform used throughout

Make sure you visit Chapter 19 (Visual Studio 2012, Explored) before you go much further with following

along with any code and script 'walk-throughs' that I have documented in these eNotes.

Get VS 2012 (version 11) and also Windows 8 - full version, with Win32 as well as WinRT.

============================================================================

I think you need to know a full description of the software platform that I have here on my development PC.

I have an old desktop machine which was a high specification years back when it was made by myself.

However, it is now looking a little dated - I use it for all my development because it seems to work just fine!

It is currently running Windows 8 - Release Preview - and Visual Studio 11 (2012) also a beta at 'RP' stage.

The SQL Server instances available to me have recently be clean up a lot, after I no longer needed to service

an old client / customer of mine. SO out went all MSSS 2005 stuff, as well as VS and Reporting Services.

I am now left with a new install of 'Denali' the codename for SQL Server 2012 from Microsoft, and this is a

full public release. I have both the full version and the 'LocalDB' version installed, as well as the support tools.

Management Studio is the main support tool I use.

Although WIn8 has yet a month or two to go before full public release it would seem, I have been using the above

software platform for a good two to three months - since June 1st. - yep! almost 3 months to the date.

I have found it good and robust and like W8 and VS11. I must have clocked up a couple of hundred hours or more,

with what I explain above, and it works very nicely. I have been almost exclusively using VS11 because Vulcan.NET

is on-hold while I learn some C#, METRO Style app development, LINQ and now EF4.

I even have grown to like the grey appearance of VS11, and it certainly does not tire the eye when using it for many

hours at a stretch.

Following Julia Lerman - programming Entity Framework - second edition :

When Julia wrote this VERY useful text, she did it against Visual Studio 2008 possibly then 2010.

However, as I have been following along with VS11 (2012) I have noticed quite a few differences, and changes.

Although it does not make it impossible for an experienced VS user to follow along, it is worth me showing enough

screen capture images at certain points inmy eNotes, just to help us all out - those using VS11 that is.

PHH - 23rd. August 2012.


Terminolgy and Acronyms Used

We all need to be familiar with many (all?) of the following acronyms and phrases :-

TPT -

Assemblies -

Namesapce -

ADO.NET

Data Centric

Domain Centric

DDD - 'Domain Driven Design' - custom classes first, generate EDM abd DB afterwards.

'LINQ to Entities' - will very likely cover a large portion of your query needs. JL

'Entity SQL' -

'ObjectQuery' class -

Object Programming -

Custom / Business Objects -

'Mapping' -

Multi-Access -

Relational Database -

DBMS - Database Management System

EF - Entity Framework

'Entity' - a data pipeline

'Binding' - a data tie

EDM - Entity Data Model

EDMD - EDM Designer (Visual Studio) software tools

'Entity Object' -

'EntityCollection' - not at all the same as a 'System.Collection' - they are not interchangeable!

'Entity Container' - logical group of 'Entities'.

POCO - 'Plain Old CLR Object'

'Attributes' - properties that describe the schema of an 'Entity property'.

[.. so 'Contact,Firstname' has a 'Fixed Length' attribute (property) value of false ..]

Object Services .... compare with Dependency System at other end of model

'Code First' -

API - Application Programming Interface

WCF - 'Windows Communication Foundation'

WPF

XAML -

XML -

DP - Dependency Property -

Dependency Object -

'Data Binding'

ORM - Object Relational Mapping

SQL

'Querying'

Stored Procedure (and Functions)

LINQ - Language Integrated Query

Back-end Data Source -

MVVM - 'Model. View, ViewModel'

MVVMLight -

MVC, MVC3 - 'Model, View, Controler'

METRO / Modern Style

'Layered Applications'

Projection - Often in SQL, you will select particular columns to return from a table

(SELECT Firstname, Lastname FROM Contact) or from a set of joined tables.

This is referred to as projection.

Eager loading

Deferred loading - When deferred loading happens automatically (implicitly), it is called lazy loading.

Navigating

PHH - 23rd. August 2012.


Learning Materials

Don't get or study any Book / eBook before version 4.0 of EF - try to get 4.3 and/or later.

At the time I am writing these eNotes EF5 is in beta form and so I expect to add a chapter or two later,

within these following sections.

The advice I had for the present (nearly September 2012) is to use EF4 until version % is in public release.

check out the 'ClickStartLINQ' eNotes

also ClickStartADO as well

PHH - 23rd. August 2012.


Books and eBooks

Book and eBook - Julia Lerman :

Make sure you get at least the 'second' edition of this book.

Julia Lerman is quite a recognised Guru and author / speaker on this subject, so I am not sure if you need

any other reference text after her edition two eVolume of this title.

I will see how I go myself, and let you know if I feel a definite need to another input source of any note.

================================================================================================

We appreciate, but do not require, attribution. An attribution usually includes the title,

author, publisher, and ISBN. For example: “Programming Entity Framework, Second

Edition, by Julia Lerman. Copyright 2010 Julia Lerman, 978-0-596-80726-9.”

========================================================================

We appreciate, but do not require, attribution. An attribution usually includes the title,

author, publisher, and ISBN. For example: “Programming Entity Framework: Code

First by Julia Lerman and Rowan Miller (O’Reilly). Copyright 2012 Julia Lerman,

Rowan Miller, 978-1-449-31294-7.”

=========================================================================================

====================================================================================

We appreciate, but do not require, attribution. An attribution usually includes the title,

author, publisher, and ISBN. For example: “Programming Entity Framework: DbContext

by Julia Lerman and Rowan Miller (O’Reilly). Copyright 2012 Julia Lerman and

Rowan Miller, 978-1-449-31296-1.”

PHH - 23rd. August 2012. & September 4th. 2012.


Web Casts / videos / web articles

Microsoft's 'How do I' videos

http://msdn.microsoft.com/en-US/data/videos

===========================================================================================================

==========================================================================================================

======================================================================================================================

http://msdn.microsoft.com/en-us/bb629407.aspx#wpf/

====================================================================================

http://blogs.msdn.com/b/diego/archive/2008/10/09/quick-tips-for-entity-framework-databinding.aspx

=================================================================================

http://blogs.msdn.com/b/dchandnani/archive/2005/03/15/396387.aspx

LINQ C# Query Examples :

http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b

===================================================================================================================================================================

=================================================================================================================

One Example : (Left Outer Join) :

===================================================================================================================

============================================================================================================================

================================================================================================================

===============================================

=======================================================

==================================================================================================================================

============================================================================================================================

Entity Framework Query Samples ( 'Entity yo SQL' ?) :

http://archive.msdn.microsoft.com/EFQuerySamples

===========================================================================================================================================================================================

Moving on :-

http://msdn.microsoft.com/en-us/library/dd380721(v=VS.100).aspx

================================================================================================================================================================

PHH - 23rd. August 2012.


Necessary Downloads

Reflector Pro - a must have

the eBook (second edition) - Julia Lerman - another must have

http://learnentityframework.com

http://learnentityframework.com/LearnEntityFramework/downloads/

=====================================================

http://visualstudiogallery.msdn.microsoft.com/df3541c3-d833-4b65-b942-989e7ec74c87/

==================================================================================================================

=================================================================================================================================

Get all six of the above.

PHH - 23rd. August 2012.


Versions etc.

==============================================================================================================

==============================================================================================================

===========================================================================================================

========================================================================================================

==============================================================================================================

====================================================================

PHH - 8th. September 2012.


Auto-X-Mapper

Okay then guys, if you think that introducing yet another new 'thing' is just a bit "over the top", then think again.

The task of mapping one class to another is yet another one of those tedious coding task - BUT - one which needs

to be done 100% correctly.

So when we get a chance to get help, and support, in such a task we can't ignore it.

To make 'Auto Mapper' to us in our project we simply need to have our project in focus in the SE pane and follow

what is seen below :-

==========================================================================================================================

When the 'Package Manager Console' (PMC)appears type in 'Install-Package AutoMapper' (without the single quotes)

and then press 'return'.

The PMC and the results are seen below :-

===================================================================================

And if you now re-look in the SE pane we see the results of the install process

in the References sub-folder or node :-

=====================================================

There is plenty of material on the web on AM to get us going, and some of this will be seen

used to good effect in Appendex H, later in these eNotes.

Here is some visual encouragement - check this out :-

=========================================================================================

We will look at material from the 'getting started guide' in the appendix section - Appendix - H.

https://github.com/AutoMapper/AutoMapper/wiki/Getting-started

Time to move on ............................

PHH - 11th. September 2012.


My Advice - after writing 'this.60%'

I am now in a position to give you guys some advice, since I have been through the text books

and explored enough EF related 'stuff' to know where I may be headed, so I will tell you want I now think.

- If you can only use Code First

- Have one custom class per data Table in the SQL database

- when making queries, use 'Query Expression' syntax and not Lambda extension methods.

- ONLY, bring data into the application that you really need.

- Do as much processing as possible, in the back-end Server, and as little as possible in the local app code.

- Keep learning as much about T-SQL as possible, knowledge about SQL will make you a better EF/CF coder.

- Keep things as simple as possible - greater simplicity means less confusing errors.

- Have more than one 'Context' class - possibly many.

- Design and structure your 'Contexts' to fit with certain types of task - this way they remain less complex.

- Do not by-pass the EF/CF and DbContext system by querying the Server directly - unless there is no other way.

- Keep the data in use on a 'Human Scale' - a user can only visually, and mentally, take on board so much detail,

so why provide more ?

- use the Fluent API to separate .NET class code and class configuration for the related SQL Table - both will read easier.

- Get very familiar with 'collections' and accessing / using their objects - FOREACH and Enumerator.

- Give up the use of the DataTable class if at all possible.

- Give up using ADO.NET directly, as a developer - let the underlying layers use it for us.

- Start to use the SQL features built into VS11 in place of Management Studio, well, at least while you are developing. There

may be times at client sites, when you may need to install and use MS itself. There ought to be an Express version of 2012

for such purposes.

- Use 'Server Explorer' and 'SQL Server Object Explorer' in VS11 - and also the New Query Tab as well.

PHH - 20th. September 2012.


Chapter 0 -

Chapter 0 - 'Out with the Old, in with the New'

Before you guys get the wrong idea about all this, Microsoft do not seem to have caused or created a

revolution. They have not scrapped anything previously important or necessary !

They have simply put layers in place which save us, the developer, having to keep re-coding the tedious 'mapping' stuff.

It would appear that ADO.NET (a very mature and well tried and tested technology) is still there and functioning well.

It is just that we do not use it directly, as the 'Entity Framework' (EF) does that for us.

Because SQL Server is a separate and well functioning back-end unit on its own, we still need our applications to

send the same sorts of Query Statements that they always did send. So nothing has changed there.

However, instead of us 'crafting' and sending the query string, we now have the 'Entity Framework' to do that for us.

We now simply work at a 'higher level' where we think in terms of our BO's and write some .NET code which has a

clean and simple syntax - which looks a bit like the SQL query statement of old.

It is time we had an example to study, and a colourful visual to lighten our 'learning load'.

View the details in the next image, very CAREFULLY :-

===========================================================================================================

Study the above image details.

Basically, the EF 'system' makes and maintains the 'bit' that is the right hand side (RHS) of code line 297.

The rest of the few lines simply sets the query and uses the returned data collection of 'Contact' objects to

fill a permanent typed list for us to use elsewhere.

Now study the small image shown below - it uses the above method to find and return all the Contact objects,

the typed list that is - check this out :-

==============================================================================================

If you are not very familiar with using ' var ' then you soon will be, it is extremely useful to us.

Basically, the type of the object (or class) on the RHS of the assignment is used by the compiler to provide

a type for the named variable on the left (LHS).

So in our example above, 'AOC' will be of type generic list - List<T> - where ' T ' is our 'Contact' class.

In Vulcan 'LOCAL IMPLIED' does the same job, and I use both regularly - they definitely have their place.

So line 17 in the above code reads as ... make variable 'c' equal to each in turn of the objects in the collection

called 'AOC' and use it in the loop.

Be aware that the enumeration which is allowed for the 'collection' object itself, may be Read/Only and also

forward only as well, as it is shown above. You need to check this for yourself.

However, we can set things up for ourselves if we wish to have more control over pointer movement.

Okay then, a short summary, did we see in the above images and signs of Tables and Rows, or Columns either?

The answer is a definite NO.

Did you see any obvious signs of ADO.NET being used? Once again the answer is NO.

Did we see any signs of 'Collections' and Business Objects, and 'Enumeration' - yes, lots!

Did we see any LINQ syntax? yes, we definitely did (lines 299 - 301, which was the nub of the whole code).

Well, that's what it is all about :-)

Because our standard LINQ syntax use the RHS 'original' collection from EF4 it is called 'LINQ to Entities'.

However, to you and me it just looks like the 'clean' syntax for LINQ. More on this in later sections.

So where has EF4 saved us time and lots of tedious hassle ?

Well in the making of all the 'stuff' which gives us the RHS of line 297, the 'SampleEntities' in this example.

In the next section we will look at how we take a simple and existing (legacy?) database and get EF4 to do

the work of making the RHS 'bits'. It is easy and quick.

Persisting our Results - a point to note ! :

While we are at this introductory stage I feel it is VERY important to point out that a LINQ query is only made

active, and used to query the SQL Server 'physically', when its return variable is actually used in further code.

However, the converse is also true, each time we use the LINQ variable, the database is physically queried.

To get around this latter problem / issue, we can wrap the LINQ query into a method as seen above, this can

then be used once to create a List<T> object which can be associated with a property on a custom class.

From then on the property may be re-used, over and over, without re-sending the query to the back-end source.

However, we can write our code to re-use the method when we wish to do so.

Making changes to our objects and having them persisted to the data source is handled by the 'SampleEntity'

stuff in this case, and all we need do is request to keep the changes.

Lets look at a simple example of this, changing data in code and saving it back. Checkout the following :-

========================================================================================================

In the above image line 53 forces the changes to be persisted to the DB source. These will just be the changes

occurring since the instantiation of 'context' on line 45, in this example.

The 'using' statement means that the scope of the variable named 'context' is only lines 47 through 54.

The EF4 stuff handles the rest - keeping track of what objects in memory have been changed, and which properties

within them have changed too. Only the changes are sent back to the source.

So that we are dealing with the EF4 'stuff' we always need to use the 'context' as shown above - BUT - be aware

that for a real live world application, we may need to instantiate only once - right at the beginning of our app - so that we can

track all the changes across the whole of the lifetime of the app. It all depends on what we wish to happen - the design

plan or philosophy that is.

We will need to explore this aspect later as there may also be times when we just want to track immediate changes,

and therefore we may need to have multiple instances of the 'context' EF 'thingy' in use. Close some immediately, and

still have others open. It will all become clear as we go along.

PHH - 26th. August 2012.


Chapter 1 -

Chapter 1 - Entity Data Model (EDM)

 Top Previous Next

Okay then you guys, a simple and obvious 'first question' - what is an 'Entity' ?

A simple enough question, but it is NOT easy to find a straightforward answer.

I have a simple idea which I often apply - if an author uses long sentences they are struggling to understand

what they are describing ;-0)

MSDN docs :

The latest MSDN docs has this to say before it goes off into gibberish :-

An Entity object is a business object, such as Customer or Product, in line-of-business (LOB) application.

To my eyes this does not even read correctly, and this is the simplest bit I could find.

Where on earth did the last part of this sentence come from ?

Now over to Wikipedia - well its worth a laugh :-

Wiki - Entities :

Entities are instances of EntityTypes; they represent the individual instances of the objects (such as customer, orders)

to which the information pertains.

The identity of an entity is defined by the entity type it is an instance of;

in that sense an entity type defines the class an entity belongs to and also defines what properties an entity will have.

Properties describe some aspect of the entity by giving it a name and a type.

The properties of an entity type in ADO.NET Entity Framework are fully typed, and are fully compatible with the type system

used in a DBMS system, as well as the Common Type System of the .NET Framework.

A property can be SimpleType, or ComplexType, and can be multi valued as well.

All EntityTypes belong to some namespace, and have an EntityKey property which uniquely identifies each instance of the entity type.

Now what Julia Lerman says in her book - well it is a little better, perhaps :-

Julia - Entities :

==============================================================================================

=============================================================================================

A little better - BUT - we still need to make things a lot clearer for a standard guy like me !

My 'humble' Attempt :

Being a scientist I was brought up on definitions - learning them and applying them.

So lets try and make some sort of a definition, based on what I have read in Julia's text, MSDN, and web

articles too.

Definition :

An 'Entity' is a .NET class (or object) which sits between the data tables and the business classes in our

applications.

Because it sits 'between' these two 'things' it has aspects of both, and it allows us to always work with .NET

code and 'objects'. Tables, rows and columns are completely hidden to us when we use an 'Entity'. However,

the properties of an 'Entity' show a remarkable similarity to columns in the table(s), and their attributes of data

type, length and so on.

An 'Entity' can relate to one or more tables, but commonly I suspect just one - this depends on the design of

both database and your custom / business objects. Application 'stuff' designed from scratch will tend to have

a more one to one correspondence than when we have to use legacy databases I feel.

The purpose of the 'Entity' is to provide facility for 'two way' data movement, between the application and the

data source.

So LINQ queries are run against an 'Entity' - or perhaps a collection of them to be more precise.

As well as allowing both reading and writing of data values, the 'Entity' tracks all changes made during its

instantiated 'lifetime'. This facilitates an easy way to update and insert values from our application into the

data source.

The scope of the 'Entity' does not have to be across the lifetime of the application.

If no 'Entity' is instantiated, or in scope, then no data transfer is possible using the EF approach.

It is possible to have more than one instance of the same 'Entity' tracking different changes to the same data

tables. Because data value changes are made against an 'Entity' object, only those changes are tracked.

So if two similar 'Entity' objects are in scope, changes made against one will be totally unknown to the other.

So to summarize, an 'Entity' is a data pipeline.

To add to this definition we need to realise that we usually have a bunch of 'Entities' and this makes up the Model.

So we have one EDM which 'contains' a number of 'Entity' classes.

It is also quite possible to re-use the EDM with other projects based on the same data source.

Enough for now, time to move on ......................

PHH - 31st. August 2012.


Making a start - basic explanation

Okay then guys, now we have a definition for an 'Entity' we need to read it several times before we do

any creative design work.

Remember, "An 'Entity' is a data pipeline."

Now, if we understand our definitions or not, we will be judged on whether we can create .NET code which

makes all this stuff work for us.

Sometimes it is easy enough to get a hang of the syntax, and copy and adapt examples, so that we get code

which runs nicely in our business applications.

Using Lambda expressions in Extension methods is one good example - we do not need to know the definition

or the roots of Lambdas to be able to get suitable results every time. However, knowing what an 'Entity' is, seems

to be much more fundamental to me for using the 'EF' correctly.

'Entity Data Model' - EDM :

Okay then, so if we think of an Entity as a data pipeline, then the EDM or 'Entity Data Model' must be a way of

developers setting up these data pipelines from data to Model. The 'Model' will contain a set of Entities (or pipelines).

Tables and columns in the data source are 'mapped' with items in the 'Model', and the 'Entity' is made by the VS 'shell'

from this set of mapping relationships. One set of mappings within an Entity will create one pipeline.

If we take an overall view of what we develop in the next few chapters (Julia does it in chapter 2) we can see just what

an EDM is, and how it arises.

Lets start at the data source end - see the following details and study thoroughly :-

===============================================

[ .. 'ProgrammingEFDB1.mdf' is Julia's sample database .. ]

Yes, we seem to have two tables and a 'view' - which can be thought of as a Read / Only table.

And at the other end of things, in the 'Model Designer' surface we see the following :-

[ .. note this is often called the Model diagram .. ]

=========================================================================================

And the 'bit' that is generated from the Model 'mapping' is shown below as a highlight :-

=====================================================

And now we can look inside the file shown above in highlight - see below :-

[ .. this is the class for the 'Entity' Set ' itself .. notice it is a 'ObjectContext' type .. ]

=================================================================================================================================

If the above is effectively the 'Entity Set' then where are the 'Entities' themselves ?

Well they are in the same file and come next, just under the 'SamplesEntities' class.

Look at the following in close detail :-

==========================================================================================================

Notice that the VS code has the #region set to 'Entities', so Address, Contact and vOfficeAddress are our three

Entities. (Three pipelines in our terms.)

Now lets see how we can instantiate this "entity set", or 'ObjectContext', and start to use it as the 'data pipelines' that it is.

In the following image look in particular at line 419 where we instantiate 'context' as a 'SampleEntities' class object.

=============================================================================================================

In line 426 we use 'contacts' once to make our own object.

Line 422 also shows how using the 'ObjectContext' we can refer to the collection of Entity classes, and then in particular

one of type 'Contact'.

The query is only sent to the SQL server when 'contacts' is used a first time. We make our own object from this so that

we do not force a re-querying of the Server each time it is used subsequently - which is it default / natural behaviour.

Now we can see our in-memory object being used, without a re-send of the query - check this out below :-

=====================================================================================================================================

In the above image we see that line 18 causes the query to be sent from the method being called. And in fact

the way we have coded things, each time we call this method the query will be resent to the Server.

To stop re-querying, we really need to call the method once, and save the returned list to our own variable, at a

scope one level above the method call, or higher. Then we just use the in-memory object.

This has been a suitable enough start to 'Entities' and the EDM, so lets move on a pace.

See you in the next subsection ............................

PHH - 31st. August 2012.


Going further - making an EDM

Okay guys, now that we know what an 'Entity' is and also how we can use the classes made by

the EDM designer to create objects for querying, we need to find out where the EDM comes from !?

Well, before we get into fine detail in the following few chapters and sections, we need an overview of

what we have, and what is going on.

Basic 'Truism' :

In order for us to by using EF4 and therefore query with LINQ against the 'ObjectContext', we need to have

a Model. Somehow we have to get or make a 'Model, or an EDM.

With EF4.3 we apparently have a lot of choice ;-) And the experts (engineers) at Microsoft have come up with

catchy names, we have :-

- 'Data First'

- 'Model First'

- 'Code First'

These are pretty simple to understand, and carry out too it would seem.

The first one applies to the 'Legacy' situation we will all find ourselves in from time to time.

When we have to hand a well developed data source, and most likely packed with active data as well.

In that case we get the templates in VS11 to use the database and to construct a Model from this.

=========================================================================================================================

The Wizard for EDM opens when 'Add' is selected - and we see the following :-

=====================================================================================

After another screen we get to select both the database and the instance of the SQL Server - see below :-

===============================================================

And when we choose to use Julia's sample DB and my 'Denali' server we see the next

Wizard screen of :-

=====================================================================================

Where the information from the 'New Connection' is gathered together.

The next and almost final Wizard screen allows us to select the database items we wish to include

in our EDM - checkout these Tables and Views, we are leaving Stored Procedures for the moment :-

=====================================================================================

Obviously when we click the 'Finish' button the VS11 system goes away and does all that is necessary

to make the EDM and it looks like this shown below :-

========================================================================================

Notice that the automatic creation has brought across the table names for Entity names, and the column

names as properties, all according to its deep down knowledge from the Microsoft engineers.

Moving on, so what of the 'Model First' ? ...............

'Model First' :

Well, this is not as complex in many ways as what we have already seen.

If we have no database on which to base our code and application we can elect to start with an empty Model.

This option was available in a previous image above, but we chose to select a different option. Below we are

choosing the 'Empty Model' - check it out :-

====================================================================================

When we elect to start with a 'blank' then we get the daunting experience of a clean and empty 'Designer'

surface, just like that shown below :-

In the above image we see that I am in the process of dragging an Entity 'tool' from the Toolbox and into the design surface.

And the result of that is as follows :-

=====================================================================================

You will see that in Chapter 7 of these eNotes we go through a complete process of design and creation, follow Julia's

excellent book.

For now we will move on to the third possibility - BUT - only after we have taken the opportunity to see that for what ever

reason we can have more than one Model in a single project within our Solution Explorer pane - see below :-

===================================================

Now, at this point I have to be honest with you, I don't know why we would have more than one, except to keep this simpler.

So that we don't get great complex EDM's for large projects and applications. At least we can see that it does not seem

to break our code or project ;-)

I have just checked my app - it still compiles and runs OK.

Moving on to business object classes first .....................

'Code First' :

Okay then, once again honesty - as yet I have not tried this even though it is supposed to be available to EF4.3 and also

we don't have Julia to guide us either. The final bits were not in place when she did her book edition update.

I will try to research this approach and see what is now available to us from both the web and from Microsoft.

Hopefully we can add some meaningful subsections into chapter 8 of these eNotes.

Having had a quick look we seem to have some possibilities - I will need to study and follow a few leads.

Check this out :-

====================================================================================

Now time to move on a pace, see you in the next subsection ......................

Lets go and see how we can query our data source using the classes created to support the EDM 'visual'.

PHH - 31st. August 2012.


Chapter 2 -

Chapter 2 - Querying the 'EDM'

Once we have made ourselves a suitable 'Data Model' we can then use it to shape our queries for getting

data returned from the SQL Server by sending queries.

In this section we will use the EDM that Julia Lerman get us to create when we follow her book, and do chapter 2.

The queries originate in our .NET code, and are coded by us in C# syntax. We do not write and test SQL query statements

in Management Studio any longer, and send these as strings from our .NET code as we did when using ADO.NET directly.

I have to confess I did this a lot, and for a few years - the new way is better !

=========================================================================================

After my research into LINQ syntax, and the possibility for using Lambda Expressions as an alternative, I will endeavour

to keep this sections as simple as necessary.

Generally we will work with (and use in real examples) the now standard 'LINQ syntax' and not the Lambda driven extension

method calls.

However, we need to know all about these method calls as we can, if needs be, do just about anything we require with them.

Here is what Julia has to say :-

=========================================================================================================================

She then goes on to say this too :-

========================================================================================================================

Before we look at the alternative syntax, we need to see and study what Microsoft recommends as the simplest, or

the cleanest syntax.

Below is such a 'standard' LINQ syntax query - note in particular lines 23 through 26 :-

================================================================================================================================

The above code syntax is what I prefer to use if at all possible, and this is what Microsoft recommend.

However we need to know how it looks with Lambda method calls too, and I suspect that this is what is used when the

query expression is translated ready for the CLR ;-)

Checkout the alternative syntax :-

=========================================================================================================

In the above image the old lines 35 and 37 have been commented so you can compare.

The results are from the new style code 'as-is' - that shown in the image.

There is a lot more information on Lambda Expressions, and using Extension Method calls, in the eNotes

entitled 'ClickStartLINQ' - I suggest you consult them and have a read through.

I also suggest you study the these LINQ notes before getting too deeply into EF4. Because I did most of the work on LINQ for

these eNotes before coming to EF4, it has made my life a lot simpler. I recommend you do the same.

A fuller (finished) version of the Lambda method call syntax is shown after we look at making a more complex filter

condition within our WHERE clause.

In case you are new to SQL stuff, the 'WHERE' clause is know as the 'filter' condition(s).

Checkout the following image, and line 31 in particular :- [ .. first in Query Expression syntax .... ]

=======================================================================================================================================

And now we can see the same query but using the Extension methods and Lambda expressions :-

[ .. checkout lines 34 through 36 .. ]

==========================================================================================================

Notice the difference in sort order, the first is ascending and the second one descending - checkout line 35 above.

Here is some useful information :-

LINQ actually evaluates the query one method at a time.

First it evaluates 'context.Contacts'.

Then it applies the 'Where' method to those results.

Finally, it applies the 'OrderByDescending' method to the results of the 'Where' method.

The c in the 'Where' method refers to the items returned by 'context.Contacts'.

The c in the 'OrderByDescending' method refers to the IQueryable that is returned by context.Contacts.Where(....).

In the 'Select' method some, or all, of the 'c' is returned - in this case the whole of 'c'.

*** NOTE *** when we talk of one method being applied after another, we are meaning that this is what the compiler does,

it is not us saying that the successive operations are done on the data !

We need to understand this, as only one SQL statement - or query - will result in the compiler 'doing its stuff', so that

one efficient query will result from all this - and then sent to the SQL Server via ADO.NET calls.

Yes, we need to remember that it is ADO.NET technology which communicates with the data Server.

Now then, time to investigate something else, how do the Lambda 'c' items affect one another ?

Well, I have made up my own test code below, just to demonstrate a few points - check this out :-

============================================================================================================

Notice that in the above example lines the consistency of the letters (characters) used in the Lambda expression

applies to the individual expressions - that within the braces.

You can see I have used X, Y and Z in the separate lines.

And below we experiment further - sorry that line 31 now refers wrongly to line 26 when it ought to be 30 !

Here we need to note that we can actually use variables within the filter clause - boy and girl are declared

string variables - see below :-

[ .. once again line 31 should refer to line 30 and NOT 26 ! .. ]

====================================================================================================

And we can do exactly the same in the extension method Lambda input parameter - see the next image below :-

====================================================================================================================

Now for some simple fun ............... ;-0)

The Simplest Possible Query :

What can this be ? All we what is the complete list of all item objects in the collection - see below :-

=================================================================================================

Yep! a one liner, that of line 210 in the image above.

A variation on this is shown below - BUT - remember when the compiler works on our syntax (code) it probably reduces

it to the same thin for both - then sends it to the CLR.

Checkout lines 210 and 211 below :-

=========================================================================================================

[ .. wrong reference in line 213 it ought to refer to line 208 and not 211, sorry ! ..]

Time to move on ................

Final Query Format - and Sending to SQL Server :

Julia has this to say about the final part of the sequence, or should I say 'process' - one end being LINQ syntax, the other

being an ADO.NET request to the server.

In the end it is the actual ADO.NET provider - for example, System.Data.SqlClient - that builds the actual

query string to be executed by the database.

The Entity Framework team put a great deal of effort into improving the SQL generated from the .NET 4 version of

this product.

If you are using the SqlClient provider that is part of .NET 4, it has been enhanced to produce more efficient T-SQL.

***************************************************************************************************************************

A key improvement to look for in the T-SQL generated by System.Data.SqlClient is smarter translation of

queries that use 'StartsWith' or 'Contains'.

In .NET 3.5, Contains was not even supported.

However, if you used 'StartsWith' in a query - for example, Contacts.Where(c=>c.LastName.StartsWith("T")) -

the database query that resulted performed poorly in the database.

Now 'StartsWith' and its newly supported siblings, 'EndsWith' and 'Contains', all result in queries that leverage

T-SQL’s LIKE operator, which takes advantage of indexing in SQL Server.

So the syntax we use for query expressions is translated eventually into a correct T-SQL script string which is sent to the

Server using ADO.NET members.

Obviously, anything returned in the way of data is then converted into a suitable object, or list of suitable objects.

We now need to see that we can pass the returned data into our own declared object - see line 217 below :-

======================================================================================================

now read on ............ this is important .........

Here is JL's advice :- (I suggest you read the full section in her book)

Once you have executed a query, you will most likely want to work with the results and no longer

the actual query.

When querying for sets of data, I recommend calling 'ToList()' to force query execution and provide a

variable to work with - from then on.

I use 'ToList' and other methods throughout my book to avoid accidentally repeating

query execution. This is my practice in production applications as well.

Note that we will need to heed her advice - BUT - we also need to be careful how we do this.

If we just wrap the code up into a method and call the method each time, we are still carrying out the query.

So we need to call the method ONLY when we wish to run the query, and otherwise store the returned data into

an object outside of the method being called.

You will see more of this as we go along, and develop our skills with EF4.

Time to move on I feel, see you in the next subsection ......................

PHH - 23rd. August 2012.


Going further - Querying

PHH - 31st. August 2012.


Chapter 3 -

Chapter 3 - 'LINQ to Entities' - going further

'Projection' :

==================================================================================================

Anonymous Types :

===============================================================================================

=======================================================================================================================

===================================================================================================

The editor / intellisense system in VS11 seems to be slightly confused as the 'select' in this format is NOT shown as red.

Somehow the presence of 'let' seems to throw it - BUT - it does compile and run, as you can see.

And now after messing around in the editor it seems to have got itself sorted out - BUT - we have another issue

it would appear - checkout below :-

=======================================================================================================

After more thought and reading, it appears as if I was doing silly things above !

Getting things Right :

===========================================================================================================================

===========================================================================================================================================

========================================================================================================================================

PHH - 23rd. August 2012.


ToList() - and Re-Shaping data

An IMPORTANT idea to get straight in your mind :

When reading helpful texts and learning material we often see many examples where after the query we

have a FOREACH loop displaying data in a console window - and things are left as that !!

In the following image from 'DbContext' by Julia Lerman et al, we such an example. Check this out :-

=======================================================

This may well be very useful to getting some quick test results, and seeing LINQ in action - BUT - from

a developer's point of view, when we are headed towards more complex data binding scenarios with WPF

and MVVM, then we need to see how to create an object from the returned data that we can pass on to

other methods, as well as return from a 'Get' type of method.

In my Olympic Games demo app we see later in these eNotes, we require to find (or Get) a list of all the

Nations within the data tables of our database.

In order to 'package' up our returned data we need to use 'ToList()' as you can see below :-

=================================================================================================

In the above image, what exactly is doing on ?

Well, lines 90 through 93 define a LINQ query expression, but this is never evaluated until the code execution

requires some data from the return data set.

Both FOREACH and 'ToList()' force the query execution because they require data.

However, if we are to use the data in other places in our code, without re-querying the data server, we need to

'cache' it in memory in some way or another.

The above code does this by converting the data returned into a List<T> object which can then be passed by

reference out of the calling method and say then bound to some GUI control, as I have done for the Olympics

application.

So just what have we got as the 'aLN' variable above ? The answer is provided by the intellisense within the editor.

See what we get as a tooltip when we hover over the variable name with the mouse pointer :-

========================================================================================

So quite simply we get a List of strongly typed 'Nation' objects. We can then use these for binding as see below :-

==========================================================================

And the results of this binding is dramatic indeed - see the following image :-

==================================================================================================================

Each of the four list controls is bound to a different List collection object.

The binding script in the XAML is seen in the next image - check this out :-

=====================================================================================================================

So effectively the four cached List<myObject> objects are bound to a specific GUI list control.

Okay then, all very useful - BUT - sometimes we will need to have a list of items returned, and passed on into

a cached state, which are not our basic objects upon which we based our Code First 'DbContext' class.

In these cases we need to what is called 'Re-Shape' the data into another class.

Time for the next subsection ......................

Which Objects do we cache ? - what is the Class ? :

So that we understand what we are doing, and what our problem really is, let us start by examining in detail the specification,

or definition, of our 'OlympicsContext' class - see below :-

=================================================================================

If we look at the 'Entities' shown above, we see that the 'Athletes' entity is based on the class called 'Athlete'.

This is our class, and it is defined as shown below :-

==========================================================================

Now all the properties seen in the above image, were provided so that the correct relationships

would be put in place when Code First makes the SQL database.

The PK and FK relationships can be seen in the following image from Management Studio :-

===============================================================

That is all good and well - BUT - the class of object that I need to proved for my GUI binding on the bottom right

combo box (drop list) is actually more complex than the Athlete class for the Entity specification.

Let us now see this new class, and remember as you check it out that it is really a 'holder for data values'.

We will explain more about the data holding issues later - first check it out below :-

====================================================================================

Lines 248-251 above show four new properties over the original 'Athlete' class.

Also we see that line 260 and 268 are no longer required as these were for CF and specifying

relationships in the SQL tables.

okay then, so we have a more complex 'data holding' class to bind to our GUI form, and individual controls,

but how do we create (or fill) such classes ?

Time to move on and look at 'Reshaping' ............

Using 'Reshaping' to create 'Binding' class objects :

For those that do not yet know it the 'MVVM' way of things, is to have 'ViewModels' to bind to the 'View'.

The 'View' is the GUI forms, the 'Model is our group of Entities making up our 'Context', and the 'View-Model' is

the very thing we are focusing on - the more complex class / object made up from one or more Entities within the Model.

MVVM stands for "Model, View, View-Model".

So the 'Model' is the results of our Code First and EF4 activities, and creation of the 'View-Model' can be done by

the 'Reshaping' we are to look at now - and/or the use of Auto Mapper type 'add-ons'.

Let us now look at the LINQ query expression which I describe here as carrying out the 'Reshaping'.

Study the following image very thoroughly and carefully :-

=================================================================================================================================

In the above image we see that we are now using our new 'View-Model' class (as I describe it) called 'AthleteFull', to

accept the items within the returned data collection.

We need to have a defined class, as anonymous types are NOT allowed when it comes to using the extension method 'ToList()'.

Since our only other options to creating and using our our complex 'View-Model' class is to use 'Athlete' or an

anonymous type in our query, we seem to have no alternative ;-) "Rock and a Had Place ? "

If we are to create a 'GetCollection' type STATIC method then we need to specify a return type, and making a List<T>

from anonymous type seems to be a 'no-no', or an impossibility :(

If we examine the next image we see that the 'ToList()' will work okay on the anonymous type collection, but that we needed

to modify the STATIC method such that it will not suit our needs - check this out below :-

===========================================================================================================================

Anyway, we need to take on board the idea that there will be times at our GUI where we need to make 'new' instances

of the same class of object we already are viewing, and an anonymous type is just 'not on'.

Let's have another way of looking at our 'LINQ query expression', it is as follows :-

=========================================================================================

This way it is very obvious that we are instantiating a bunch of new objects from the 'AthleteFull' class specification,

and providing data item values from the returned collection items.

If we look at the following result of our efforts, we see that the displayed 'template' uses every one of the above properties

except the 'GenderE' one which for some reason I have missed off !?

Lets see what we are using before we experiment any further, check out Rebecca :-

=============================================================

Now we can comment the gender and see that we still get the correct result at runtime. Here is the code

shown below (you can take my word for it that it works OK) :-

==================================================

On the other hand it would be best for our Olympics application if we now include the gender

as we can see in the following image :-

===========================================================

This was brought about by adding one simple enough script line to out XAML - see the next image :-

=========================================================================================================================

Time for a summary ...............

To Summarize :

If we are to create 'View-Models' for GUI data binding (or other) we need to use 'ToList()' and to have a defined 'more complex'

class of object than the ones used in the DbSet() definitions to define our Entities and our 'Context' class.

We will now move on to see that ToList() does not effect the data tracking the EF does for us, we can still makes changes and

save them when we decide we wish to.

Lets move on to seeing how to do changes ........ see you there ..................

PHH - 13th. September 2012.


ToList() - and Making / Saving changes

Although the next chapter, number 4, entitled "Modifying with LINQ" deals with editing existing data records,

and adding new ones, we do need to comment on how 'ToList()' fits into this updating and tracking generally.

It is important for us to know that just because we effectively 'pass' our returned collection set over to another

variable with the .ToList() extension method, does not in any way change the state of the tracking of the data

changes by the EF system.

Experienced guys will know that assignments effectively just pass pointers to existing in-memory objects, not

making copies of them unless a special 'Clone' method is used.

Since all that .ToList() actually does, is give us a cached object, which we can refer to anywhere in our application

scope (if we design things correctly) by variable name, then we would not expect this to affect the behaviour of the

'Changes Tracking'. It is the object and its properties which are being 'watched' by EF for changes to happen.

Don't Forget :

because we can change the state of the tracking being carried out, we need to remember that the object we get

after using .ToList() will only respond to tacking in the manner dictated by the EF 'Configuration' and 'ChangeTracker'

settings.

In the following image we see that 'auto tracking' has been turned off, and so this will equally affect our collection

object as if we don't use the extension method .ToList() - checkout below :-

=======================================================================================

As you would guess, or imagine, the default setting is 'true' and changes are tracked as routine - or normal practise.

So if we don't turn off the tracking then this setting will be 'true' and tracking will take place.

A Simple Example :

From our Olympic Games app developed later in these eNotes, lets take a good but straight forward example.

First of all the following image shows us the 'FirstName' of the first athlete returned by our simple query -

check this out :-

=======================================================================================================

In the above image we see that Rebecca is our first athlete, and this is confirmed from the Management Studio

raw data as see in the next image - check it thoroughly :-

================================================================================

So according to this Jessica would be the next in our list by last name (surname) ascending.

Let's prove that before we move on - see below :-

=============================================================================================

And we can then make a few small changes so that we hard code a couple of changes to the names

of Rebecca and Jessica - then try to save these - see below :-

=============================================================================================

The details of the above image show that the in-memory collection object has accepted both of the changes.

And once the OK button is clicked the code, on line 158 above, will cause the EF to persist these changes to

the back-end data source.

If we now use Management STudio to view the 'raw' data we see the following :-

======================================================================

And in the above image we do indeed see 'Becky' and 'Jess' firmly in our 'Athlete' data table.

Turning Off the Change Tracking :

Since we have such a good and clear example to hand, and working, why don't we tray another and VERY

useful test, or experiment ?

Let us do the same as above (after I remake the DB) but this time have the 'auto tracking' setting turned off.

==============================================================================================

Well, as you can see above all looks to be going much as it did previously, and the changes exist in the

objects in memory.

However, when I go and look at the raw data via MS we now see the following - check this out :-

===============================================================================

Instead of 'Jess' we still have 'Jessica', and in fact no changes have been made.

I wonder if we can detect that there are no changes to be persisted, by asking the EF system at runtime ?!

Lets see what we can do.

PHH - 14th. September 2012.


.First, .Single ... and related ..

In this section we will study the use and behaviour of four operators, and these are :-

.First(), .FirstOrDefault(), .Single(), and .SingleOrDefault().

Each has their purposes, and for us guys we may also say 'strengths and weaknesses'.

Let us start out simply, and try the following runtime experiment - check it out :-

================================================================================================

==========================================================================================================

=========================================================================

PHH - 14th. September 2012.


'Joining'

Firstly we will use material from the MSDN download indicated in the "Web Casts / videos / web articles"

section of the Introduction in these eNptes.

Find download and then select - just the Joining section is required for now.

Below is what I get on my development platform :-

==============================================

====================================================================

===============================================================================================================================================

=================================================================================================================================================

Try Other Samples :

===========================================================================================

PHH - 28th. August 2012.


List<T>, returned as Properties

Now then guys, we need to get our thoughts straight about a special type of property we may well place

within many of our Entity class definitions. Those used in DbSet() to make an Entity.

I will use the working example I have to hand, to demonstrate as we go along, and have our discussion.

If we now take a look at the class definition for 'Athlete', in our Olympics 2012 application covered later,

we see that one field is defined as a List<T> and this is called 'Entries' - see below :-

==============================================================================

Code line 893 shows this property, and it is a List of 'Entry' class objects - or empty!

I say 'or empty' as the configuration class for this Entity class is like the image below, where 'Entries'

is not defined as required. In our case this does not mean it is NULL as the class specification, shown above,

also creates and empty List and assigns it also.

Checkout the configuration details below :-

==========================================================================================

So how does this all affect what we get back from our query ?

Well lets run a test method which tries to create a small collection of 'Full' athlete objects.

In the following code image notice in particular lines 217 and 224 - check this out :-

====================================================================================================================================

Now when you studied the above image details you may have thought that the " .Include("Entries") " was what

allowed us to get the values of 2 and 2 for the item count for Rebecca and Jessica. However, if we now change our

test slightly, we see that the LINQ to Entities is cleverer than that ;-0)

Check out these details :-

==========================================================================================================================

Yes, it would seem that the fact that the Enties is required to make the assignment, is enough to trigger

the EF system, and LINQ to Entities, into doing the work for us, and adding the extra facility to our SQL query

which is under the hood - under cover.

Very Useful ! - when to use? :

As you may imagine, this is a VERY useful feature of EF syntax, and can be applied in a host of different scenarios.

The classic case is for a Customer, with a bunch of Orders, and a bunch of Products used regularly. As well as these

two groups of things, the customer may have also a bunch of Address items too. So all three of these 'group' properties

may be very easily retrieved without us having to code much at all in our query expression.

Here is another simple example from our Olympic Games app., that where the Sport may have more than one venue.

Check this out :-

=====================================================================================================================================

Code line 830 shows that class 'Sport' has a group, or bunch, property called 'Venues', which is a collection

of 'Venue' objects - 'Venue' being shown above as well.

Let us now see if we have any Sports which have multiple Venues assigned to them - check below :-

===========================================================================================================================================

Yes, as you can see we now have a list which includes two venues for Athletics, Basketball, and Swimming too.

Obviously the Athletics needs the Marathon course which was down and around 'The Mall'.

And once again in the above code we see we do not need to add the 'Include' bit on line 152, it works without it

for our Code First application.

So we now have some ideas as to when to use List<T> in our classes for defining our Entities, and how to

get back the returned data. But when do we NOT try to use this '.Include()' approach ?

Joining and NOT Including :

We must not get confused between 'group properties' and List<T> use in our classes, just because the EF system

makes queries for us which gets data data back from other table. The data is still a part of the original class, and is one

or more of its properties - depending on how many such group properties you have defined.

So when we come to another scenario of getting data back from other tables, we need to call on a different technique.

When we designed and created our Code First classes, we did so to make certain relationships, using PKs and FKs.

(Primary and Foreign keys.)

Basically, PK/FK use is all about normalisation, and NOT having items of data in more than one place. To make reports,

and screen displays we most often need to de-normalise, and this can be thought of as making our data rows longer, with

more and different types of data items.

If you think of a data row (or record) as a SQL form of a .NET object, then when we de-normalise we are making more

complex objects - those with more properties.

The classic, and standard way of doing this is to JOIN table data rows - the PK/FK values are used for this.

It would appear to me that with CF and LINQ to Entities we still need to use JOIn as we did previous, and that fact that

'join' is part of the LINQ query expression syntax tells us 'all'. It is needed, and should be used by developers, and we

should design into our Entities and EDM to use this effectively.

Let us look at a good example, one from the Games 2012 application we develop later in these eNotes.

Check this out carefully :-

===========================================================================================

In the above image we see that the extra properties are filled from the joined table columns. These are

seen on lines 221 - 224, and show two filled from the Nation table, and two from the Sport table.

I won't go into the obvious details of joins and how they work, BUT, if you need to do joins then you

ought to have planned this in your CF design, so that suitable PKs/FKs exist. In standard SQL we

can join on a any two fields (columns) which are of similar type, irrespective of names of these used.

It would appear to me now, after reading much material on LINQ and EF, as well as Code First and DbContext,

that we would get our design right, and name our PK and FK fields the same etc. etc.. So we may as well

keep this section simple and short.

To Summarise :

If we wish to extend (make more complex) our returned data items, then we need to carry out JOINs, and to

do this we need existing (and planned) Primary Keys and Foreign Keys.

According to the JL et all texts, what I have termed a 'group' property is termed by them as a 'complex property',

simply because it is a group/list of objects with many scalar vales in that class of object.

Here is what they say :-

Working with DbPropertyValues for Complex Types

Let’s look at how you can work with 'DbPropertyValues' when you have a property on your entity that uses a

complex type.

Remember that complex types allow you to group multiple scalar values into a class.

A property that references a complex type is known as a complex property.

Lets move on, and learn some new things ..............

See you in the next section.

PHH - 13th. September 2012.


'Grouping' - using 'group .. by ..'

In this section we will discuss 'groups' of things, BUT, not the group we talked of when we were discussing

the 'group property' or the alternatively term 'complex property'. There we had properties which were List<T> in

nature.

Here, we will be discussing how we may use LINQ to Entities in CF to group table rows - or bunches of objects -

by certain specified properties.

Anyone familiar with SQL will know of the 'groupby' clause. Well that is what we are about here !

Okay guys, lets start VERY simple indeed ;-) Let us group our athletes into 'National' groups, so we can use the

property in Athlete of 'NationID' as our grouping field / property.

Checkout this following image :-

=============================================================================================================

So of our five athletes entered into the SQL data, we have two from one nation, two from another nation,

and the a single one from a third nation.

Let us look at the raw data in Management Studio to see if this is right - check this out :-

=============================================================================================================================================

Well, it would appear so, with South Africa (nation 11) being the single one.

Lets see if we can improve our output to help use see what is what !

Well, without any JOINs to get extra fields, we can get closer to what we have - see below :-

==============================================================================================================================

However, as you can see from the next image, since we have not got the name of the Nation in the Athlete table

then we can't print it out from our current data unless we do a JOIN - first check what we have :-

==================================================

Okay guys, it is time for a quick JOIN it would seem - check this out below :-

=========================================================================================================================================

And going that step further we can even see the last name of the athletes - see below for details :-

============================================================================================================================

Now we need to move on, now that we can at least get some suitably grouped output from our LINQ query

expressions.

I would suggest that we need to be more expert at other aspects of LINQ querying than 'group .. by ..' so

don't forget to do your homework thoroughly on other aspects, those likely to be more in demand for your

EF solutions and applications.

Time to move on to see something about 'Nested Queries' =, see you there ......................

PHH - 13th. September 2012.


'Nested' Queries

As in T-SQL itself, anywhere in LINQ where a value is expected, we can actually use another query instead.

Obviously the data type returned has to be suitable etc..

We can also use a query in place of a collection - or expression.

Quite honestly, I have found over there years doing T-SQL that the best way to learn, is to see working examples,

and then try to copy and adapt to my own application needs.

Let us revisit the same problem as we were doing in the last subsection, but this time nest the queries fro the grouping.

Checkout the following code and image :-

===============================================================================================================================================

Lines 207 - 209 are a query expression in their own rights, and all we have done is placed it where we had previous

a collection item.

This syntax works, and is allowable by the editor, because the 'inside' query will be evaluated first. Think of this

as the 'inner query'.

If you are finding nested queries hard to read, then lets start a bit simpler - BUT _ I have to confess that I find

nested queries had to get my eyes around, and have always in T-SQL reached for Functions and CTEs to help

me out - In-Line Table Functions and 'Common Table Expressions'.

Trying something simpler :

Lets try this out for 'nesting' - as a way to get out eye into scanning them :-

=======================================================

I am pretty sure that this type of example of nested queries is what Paul Nielsen called 'Correlated Subqueries', in

his Red Bible on SQL Server and T-SQL, and also his training DVDs.

The bit that makes it 'Correlated' is using part of the outer query inside the inner, or nested query.

Check this out below :-

=======================================================================================================================================================

========================================================================================================================

==================================================================================

I am showing you this because it caught me out - trying to write out one more parameter than there exists

in the available list.

The try/catch works OK.

It is line 56 which has the 'correlated reference - oa.ContactID is from the outer query.

In line 57 Julia says the Lambda driven Extension method is required because the returned value is not a 'string'

but an IQueryable of string. We need to look into this later. For now it works.

Separating then 'out' - an idea which comes next in Julia's text - BUT - I think she does not make it clear that this

can only happen if there is no correlation - no connection between outer and inner queries. So it can't be used in

all types of compound query.

==========================================================================================================

However, there is another syntax and code layout which is VERY handy.

It reminds me of one of my favourites in T-SQL, the CTE - or 'Common Table Expression'.

I have always liked simple, and clean code, and never liked long and complex lines, or multi-lines.

So to me nested statements are something I try to avoid whenever I can - hence my liking for CTEs ;-)

========================================================================================================

==================================================================================================================

PHH - 28th. August 2012.


'Shaping' returned data

PHH - 13th. September 2012.


Reloading / Refreshing, returned data

PHH - 14th. September 2012.


'Set' algebra

The word 'Set' has the mathematical meaning, as when we study 'Sets'.

It is not used here meaning set as in 'bunch of'.

So when we are looking at a subsection to study 'Set Algebra' we are talking of looking at the use

of 'Distinct', 'Union', 'Intersect', and 'Except'.

These are obviously all available in T-SQL and I use then a lot myself.

Once again there are lots of available examples fro download, from various sources, so we will just

take a couple of sample examples to allow us to remember the correct syntax - so we can try to

fashion our own queries without needing to always go elsewhere first.

If you need to know more about 'Set Algrebra' with SQL itself, then visit my 'ClickStartTSQL' eNotes

by seeing the links in the Introduction.

Distinct :

If we have a whole bunch of properties, and we wish to have just one 'inclusion' per value (say customer ID)

then we need the 'Distinct' operator.

If we learn to use this simply then we can combine its use to get more complex, possibly more usable, results.

Lets start simple.

========================================================================================================================

==================================================================================================================

=================================================================

================================================================================================================

*** Note **** For Union, Intersect and Except, we need a to have the groups of items being operated on being of

the very same 'signature'.

They items in the 'sets' need to have the same number of properties / columns, to have these of the same data types,

and also for them to be in the same order - that is for T-SQL and so I think it will be duplicated in LINQ.

Union :

Please note that if we need to have the resultant 'set' sorted in any fashion, we need to apply an extra operator. The

normal result of 'Union' is an unordered sequence.

Study the image below to see how we use the 'Union' operator in standard code :-

=========================================================================================================================================================

*** Note *** that in the line 120 above, which uses both of the arrays A and B, twice, the result is as if we had

only used them once. So we get a unique entry of each item into the resultant group.

In T-SQL we have a 'UnionAll' variant which 'sticks' the two full sets together. I will need to explore this issue

to see what we do in LINQ.

Let us move on to a slightly more advanced example - check this out :-

======================================================================================================================================================

The above code only works because the 'signature' of each item is similar - in the two sets.

Both items in P and C are single property 'string' types. Here is a more advanced form of the same query.

Study it carefully, as I have amended it and the comments no longer apply ! :-

=================================================================================================================================

Above we see that in line 140 concatenation is 'forced' because we use the 'ToString()' method.

WARNING : - 'Take good care' !! :

Now look what happens when we make a small change, which at first sight should seem to work, check this over :-

=========================================================================================================

It is not easy to show the long error messages here - AND - they do not make a lot of sense to the standard guy like you and I.

Basically, we are trying to 'merge' two sets with different signatures - one an ' int ' and one a 'string'.

Let us show what we get if we drop the 'ToString()' method - see below :-

=================================================================================================================================

So it would appear that the ASCII value for 'A' plus that for 'c' must be 97 or 98 - I guess the odd value of 97.

"OR IS IT" !!?? we shall see.

Now to check in the tables of ASCII values from the web ...............

======================================================

Nope, once we combine letters (character values) by adding we get different sort orders it would seem.

97 then 98 is simply 'a' followed by 'b' ;-)

So 97 is simply a single letter a, and 'Ac' would therefore be 65 + 99 which equals 164.

Enough of this nonsense what we MUST remember with 'Set' algebra in code (and T-SQL) is that we have to be comparing

items with exactly the same signature - or we get an error which is not that obvious to check out.

Intersect :

=================================================================================================================================

Once again, if we wish to use more than simple data types for our comparison then we will need to create and

code our own comparer

We are not going to do this here, as we should be focusing on EF4, but I will look at this in the 'ClickStartLINQ' eNotes.

Check out for it there in a little while.

Final example for this subsection - see below :-

======================================================================================================================================

Now to 'Except' ...............

Except :

Okay you guys, 'Except' will now be quite obvious to you, I should think.

If we take the first 'set' of items, and discount any also present in the second 'set', then we get an 'Except' operator behaviour.

Checkout the details in the following two images :-

========================================================================================================================================

And now some sting values - or 'letters' :-

================================================================================================================================

UnionAll ???

Time to move on, see you in the next section .....................

PHH - 28th. August 2012.


Querying 'directly' to the DB

Although this is a small section it is VERY important to many guys I suspect.

There may be times when we need to send a SQL query directly to the database behind our 'Context' object.

However, I do suggest also that you think carefully about using such a feature, and do not use it to by-pass the

EF system because you don't know enough about using Code First, DbContext, and the EF system itself.

Let us start with a snippet from Julia, just to get us going - check this :-

===================================================

Yes,

===========================================================================================================================

=================================================================================

PHH - 14th. September 2012.


Chapter 4 -

Chapter 4 - Modifying with LINQ

The disconnected model - Microsoft the web .................

'Change, but no change' ................

=====================================================================================================

==================================================================================

======================================================================================================

======================================================================================================

=====================================================================================================

======================================================================================================

PHH - 25th. August 2012.


Tracking changes, or not

===========================================================================================================

Multiple Context objects - Multi-Tracking !? :

====================================================================================================================

====================================================================================================================

=============================================================================

=============================================================================================================

================================================================================================

=======================================================================================

========================================================================================================================================================

===============================================================================================================================

=================================================================================================================================================================

========================================================================================================================================================================

PHH - 14th. September 2012.


Adding / Creating new items

===============================================================================================

=========================================================================================================================================

========================================================================================

==========================================================

PHH - 14th. September 2012.


Deleting / Removing existing items

PHH - 5th. September 2012.


Chapter 5 - Simple DB to EDM, first try

PHH - 26th. August 2012.


Chapter 5 -

Chapter 6 - full 'Legacy DB' first

In Julia Lerman's book, chapter 8, she uses a DB of her's designed for us to learn from, called 'BreakAway'.

The database is available for download from a URL shown in the introduction of these eNotes.

I suggest you download it (as well as buying her eBook of the second edition) and install it using her installer.

I so far have used her installer's for the simple DB for chapters 2 through 6, as well as BreakAway - they both

install just fine on Win8 with MSSS 2012 ('Denali').

Checkout my installation showing below in Management Studio's Object Explorer pane - see below :-

=========================================================

In the above image I have expanded the Tables node so that the individual tables can be seen.

She says that each one is relatively simple and has a limited number of fields or columns. This is simply

so that as we learn how to create an EDM from the existing (legacy) database we don't get distracted, or

too overwhelmed by the details and complexity etc..

Existing Tables :

Below are a few of these tables starting with the most complex first :-

=============================================================================================================================================

==========================================================================================================================================

The smaller table structures are as follows :-

================================================================================================================================================

=============================================================================================================================================

==========================================================================================================================================

Existing Views :

There are just three views for us to look at - see below :-

=====================================================

And when these are expanded we see the columns / fields as shown below :-

================================================================================================================================================

We can leave the Stored Procedures and anything else for now.

Let us now move on to see how we can take Julia's sample DB and do something useful with it in VS11.

I will follow through her eBook section and make it all work in this newer version of VS.

It would still be a good idea for you to purchase your own eBook edition however - see the Introduction.

PHH - 26th. August 2012.


Making a start - in VS11

=======================================================================================

=============================================================================================================

============================================================================

=================================================================================

==============================================================================================================

======================================================================================

=====================================================================================

===============================================================

================================================================

=====================================================================================

======================================================================================

In a total of about twenty (20) seconds this appeared in my Solution Explorer pane in VS11 :-

==============================================

=========================================================================================

=====================================================================================

==================================================================

==========================================================================

=====================================================================

=====================================================================

==============================================================

=========================================================

==============================================================

==============================================================

=========================================================================

=======================================================================

=========================================================================

=======================================================================

=================================================================

=================================================================

=================================================================

===================================

==================================================================

Resolving Collisions :-

==============================================================

==========================================================

Results after two other similar changes :-

=======================================================

========================================================

PHH - 26th. August 2012.


Going Further

==========================================================================

=================================================================

============================================================================================

================================================================================

=============================================================================================

============================================================================================================================================================

==================================================================================================

*** CARE *** remember to remove the ' 1 ' at the end !!!

I will now rename once more :-

================================================================================================

===========================================================================================================================================================

Destination (was Location) becomes 'PrimaryDestination', and 'Destination1' becomes 'SecondaryDestination'.

And now the other way ...................

=========================================================================================

========================================================================================

=================================================================================================

Moving to the 'Destination' entity we do similarly ..............

Here is what we start with :-

===========================================================================================

==========================================================================================

===========================================================================================

=============================================================

===================================================================================================

Setting Default Values :

From :-

===================================================================================

To :-

===================================================================================

*** Note *** standard type of Customer is equal to ' 1 '.

Julia has this to say about setting defaults in the Model :-

=======================================================================================================================

Stored Procedures - making 'Associations', or 'Mapping' :

Those existing in the DB are as follows :-

=================================================================

We are to 'map' versions for Insert, Update and Delete, of customer 'Payment'.

=================================================================================

===============================================================================================================================================

Julia says :-

First - Having a look and doing a 'basic mapping' :

======================================================

=========================================================

===========================================================================

===========================================================

=====================================================

======================================================================================

==============================================================

=================================================

======================================================================================

=========================================================

Secondly, doing the Property mapping :

=======================================================================================================

==========================================================================================

===================================================================================

====================================================================================

Now for Update ................

======================================================================================

Possibly !? - I seem to have more in my VS11 'shell' than Julia does - see below :-

[ .. compare with her page 176 details - sorry, I think I am getting confused !! .. ]

=================================================================================================

Julia said :-

I seem to have had to do a few more than this to make the screen image shown above, so maybe I am not as

confused as I thought !?

Using Original Values - 'CheckBoxes' :

Apparently we need to take this information on board :-

Okay then, I have done as instructed and here is what I have in VS11 :-

===========================================================================================================================================

I have to admit that this mapping work (changing details) is rather tedious while following along with another's

instructions. I feel it will be much easier when the DB belongs to you, the developer, or at least you know a

client's DB well.

Summary - So Far :

Well, the task of 'mapping' may always be a long and detailed one, in many ways, BUT, I have to say that the

'designer' surface of VS11 is really neat, and very nice to work with, I think is should prove to be very productive.

Also, while talking of the design surface, I feel it may also have a lot to offer when we try a 'Model First' approach.

It seems to me that we should be able to start with a 'clean sheet' and design our whole model, and have the 'shell'

of VS11 make the new database for us, to match completely the Model we are building. We need to see about this

later in our notes, and when we have read more of Julia's book.

Thankfully, it would appear that we have done enough for now, and Julia has this to say before we head for the coffee

jar and the kettle ;-)

=======================================================================================================================

PHH - 27th. August 2012.


Many-to-Many, Relationships

*** Working with the Model Diagram - some features ***

Julia says the following :-

Join Tables :

Remember, Events are Trips ! :-

===============================================

===============================================

========================================================================================================================

==================================================================================

16 in all, and that includes the 'views', so we must have ' 2 ' (two) missing - which we see in the Tables list

within Management Studio.

======================================================================================================

==================================

PHH - 27th. August 2012.


Building an Assembly

======================================================================

Use the Build / rebuild menu options after a right mouse click for the context menu :-

[ .. but first makes some changes recommended by Julia .. ]

=====================================================================

===================================================================================================================================

========================================================================================================

=====================================================================

=====================================================================

=====================================================================

Rebuild the Solution / Project :

Remember, use the Build / Rebuild context menu options - do NOT use Start or F5 !

=====================================================================================

================================================================================================================================================================

=============================================================================================================

==================================================================================================================================================

==============================================================================================================================================

==========================================================================================

===========================================================================================================================

=====================================================================

======================================================================================================

Changing back I get :-

==============================================================================================================================

AFter cleaning and build/rebuild - ing I get this !?

============================================================================================================================

PHH - 27th. August 2012.


Data Binding to a Windows Form

============================================================================================================

==============================================================================================================

Next 3 steps common to any application needing an EDM in a class library / external or other assembly.

===============================================

Julia's instructions are for VS2010 (VS10) and are different to those shown below for VS11 - study carefully :-

==============================================================================================================

==============================================================================================================

===============================================================

============================================================================================================================================

============================================================

=======================================================================================================================================

==================================================================================================

Note the appearance of 'Recent' on the LHS of the above image.

======================================================

=======================================================================================================================================

========================================================

=====================================================

================================================================================================

========================================================

Julia has this to say :-

========================================================================================

Data Sources 'WinForms' :

In this application, you will be creating data sources that bind to objects—specifically,

to the entity classes that were dynamically generated from your EDM. An Object data

source won’t bind to the entire EntityContainer; it will bind to only one individual

class.

'Object' Data Source for the Customer Class :

========================================================

=================================================

===========================================================================================

=======================================================

==============================================================================================

========================================================================================

Well - I did what JL suggested and dragged !!!

========================================================================================================================

=========================================================================================

=======================================================

==========================================================================================================================================================================================================

I have now deleted what I have done and gone back to following the test !

=================================================

=============================================================================================

===============================================================================================================================

==================================================================

Drag from the Toolbox a 'BindingNavigator' control, and drop it on the Form grid somewhere empty / clear.

======================================================================

Use the Properties Pane to make the binding connection and change the name too.

=========================================================================

==========================================================

Getting some Data returned :

============================================================================================================

Some Working Results :

================================================================

PHH - 27th. August 2012.


DataBinding to a WPF form

================================================================================================

=============================================================================================================

================================================

=============================================

============================================================================================================

===============================================

==============================================

=============================================================================================================

==============================================

=============================================================================================================================

==========================================================

Drag and Drop - with modifier key depressed ( 'Ctrl' ) - this copies !!

==========================================================

Should give the following result in the SE pane :-

============================================

Julia says :-

=====================================================================================================================

===================================================================================================================================================

Adding Data Source Objects :

==================================================

===========================================================================================

Choose 'Trip', Lodging' and 'Destination', as seen in the next image shown below :-

===========================================================================================

==================================================

==========================================

Julia says :-

===============================================================================

=======================================================

============================================================================

================================================

==========================================

And now when we first look into 'Lodging'

==================================

==========================================

==========================================

The icons show two combo boxes, one ListBox, and the original DataGrid has now gone - is not showing.

Do NOT do any DnD stuff as yet !!

Julia says we need to get his in the correct order - so wait, then read on :-

Drag the Data Sources (DS) from the DS pane onto the design surface in the order 'Destination' first, then 'Lodging',

and then finally 'Trip'. Obviously this is 'Drag and Drop'.

============================================================================================================================

==================================================================================================================================

=================================================================================================================================================

======================================================================================================================

=====================================================================================================================================================================

=========================================================================

This is why we dragged the 'Destination' source object first - see below :-

===================================================================================================================================

The other two are different and show as follows :-

=======================================================================================================

======================================================================================================================

=======================================

=========================================================================================================================================

[ .. strange !? - there ought to be three of these sections, the one for 'trips' is missing ..]

[ .. we will attempt to put this right later on, fingers crossed !! .. ]

========================================================================================================

After inputting the details from JL's book (around pages 217/218) i got some errors showing as seen below :-

============================================================================================

=========================================================

The best I can guess at is this shown below - well at least it should compile (perhaps) !?

===================================================================================

Yep! just tried it and it compiles and runs - of course we don't see any data items / values on the form as we have not

as yet completed our set-up from Julia's text. Lets continue :-

============================================================================================================================

[ *** CARE *** just a warning, this this entry that I hand crafted is not yet correct - Julia and I both made a typo or two !! .. ]

===================================================================================================================================================

====================================================================================================================================================

Problem Solved :

Got it - found the right name text characters - see below :-

============================================================================================================================

Looking Better :

===========================================================================================

'So far so good' - but we do have a few problems when we compare it to JL's master in the text.

We appear to have some incorrect GUI controls - we will need to correct this by XAML coding directly.

PHH - 28th. August 2012.


Chapter 6 -

Chapter 7 - 'EDM' or 'Model' first

The last chapter where we used a legacy database to create everything else from then on, was an

approach called 'Database First'.

This type of modelling will be often required simply because we need to use existing DBs.

However, Microsoft are also providing us with a facility in Visual Studio to carry out a 'Model First' approach.

This means we start with no SQL database, and use the 'blank' EDM designer surface to create a new model. From

that 'new model' we can then get VS to make our SQL database for us - very neat!

But, if you think that is cool, then what about 'Code First', a technique with which we start with a 'blank canvas' and

then design and create our business and custom classes, then get VS to make both the SQL database and the Model

for us, at a stroke ! (or two).

Although we will study 'Code First' in the next chapter, look at this I just found on the web :-

http://visualstudiomagazine.com/articles/2012/03/07/an-ef-code-first-tutorial.aspx

=================================================================================================================================================

So from the information shown above it would appear that we ought to be able to do 'Code First' with our EF4.3 plus versions.

Okay then guys, lets make a start, and try to follow along with Julia Lerman, and her excellent book (well eBook too).

Getting Our Heads Around all this :

Let us get a few things correct from the start.

The 'Model First' approach is now a viable concern simply because Microsoft have improved their Visual Studio environment.

By this I mean that MS have improved their earlier design tools and we can now successfully design and create a Model on

the design surface, then let the in-built tools build both suitable 'metadata' as well as a SQL database.

Julia says this :-

The Entity Data Model Designer (EDMD) supports creating entities, relationships, and inheritance

hierarchies directly on the design surface.

The code generation will continue to perform its job of creating classes based on the model.

But the conceptual model still needs a backing database along with the additional metadata

—store schema and mappings—in order for the Entity Framework runtime to do its job.

The Designer’s context menu has a Generate Database from Model option.

But this is a bit of a misnomer.

This feature will create the necessary SQL to define tables and constraints for a database.

This is called the Database Definition Language, or DDL.

But it will not create a database and it will not automatically execute this SQL.

It will only build the DDL for you; it will be up to you to execute the DDL.

If you want more of Julia's good advice and information I suggest an on-line purchase of her eBook, very good read indeed,

even if it is a bit hard going to start with - but that's the nature of this game of EF !!

Once we have been through the first example - that from Julia's fine text book - we will then move on to

do our own thing, and really make an SQL database from scratch - all on our own ;-)

We can then use this for some earlier sections in these eNotes, yet to be completed on querying in different ways, as

we will not make anything too complex or difficult to understand.

This new DB may well stand us in good stead for other later testing and trialing too.

Now to move on the the fun bit - creating a new EDM without any database to build upon.

See you in the next subsection ...................

PHH - 29th. August 2012.


the 'ConferenceManager' app.

The 'ConferenceManager' application :

Remember that Julia was using an earlier version of VS as well as an earlier version of EF, and so I will try

to smooth things out as far as any differences are concerned, as we go along.

Here is what Julia's schematic of the 'Model' is like :-

=======================================================================================================================

With VS11 (called Visual Studio 2012) let us close down any open solution / project, and start afresh.

==================================================================================================

Now we need to start a new Class Library project - see below :-

===========================================================================================================================

The results of this can be see as :-

===================================================================================================================

Now to add the EDM (ADO.NET) item into our project :-

==============================================================================================

Notice some of the input details I have added to the dialog screen - see below :-

===========================================================================================================================

And when the 'Wizard' comes on screen select the 'Empty' model option - not the existing DB option !!

=====================================================================================

Then if you have done all that OK you will have something like the following - note the message in the designer 'Diagram' tab :-

=====================================================================================================================================

Since Julia says this about 2008 and 2012 VS versions :-

=======================================================================================

Then i suggest that this means with our VS11 (2012) we should have lots of advantages, and much more

should work nicely for us - fingers crossed !?

Lets have a look at our Toolbox, and see how it compares with earlier VS versions - check below :-

=======================================

Not surprisingly, this has not changed, the same items are still required as previously - we

just hope that the supporting behaviour of the Designer has improved ;-)

And now lets see what the context menu is like for the blank designer area :-

=================================================================================================================

Now to make some 'new stuff' ............

Lets be Brave !? :

Okay then guys, let us take a different path to Julia and her text book.

If the VS11 has improved that much more than earlier versions then the 'Designer' itself should be good, and a joy to use !

Well, at least we can give it a go.

Drag an entity onto the blank surface as shown below :-

===========================================================================

CARE - WARNING - to remove items from the Designer surface use only the Designer context menu options.

DO NOT try a do-it-yourself 'thing' with items in the SE pane or even worse, the WE folder etc. :(

I know I just tried it - am now starting afresh to make the project :((

Luckily I had not invested a lot of effort !

I think it is a good idea to read carefully, this bit from the VS creators :-

============================================================================================

Here is the Model Browser, I suspect we will use this a lot some time later.

==================================================================

Now to try a a fresh Drag from the Toolbox - of an Entity - here goes :-

========================================================

According to my previous research efforts - an hour or so back, we ought to be able to use the Properties Pane (PP)

whenever Julia uses a context menu dialog from her earlier VS version.

When the new entity is in focus we get a PP like this :-

=========================================================

So we could change Name and Set Name it would appear.

However, if we click inside a Property 'area' on the designer item image - see below :-

=============================

We then get a PP looking like this which follows :-

=========================================================

Which seems to open up some of the other fields for value entry that JL showed on her dialog graphic.

Lets now click the Entity image to give it focus, and then use the PP to change the name to 'Speaker' as

we are instructed by JL.

=========================================================

I tried to capture the screen after I added the 'Speaker' text but in doing so the above PP

lost focus and automatically changed the set name and with an 's' on the end too.

The Designer surface looks like this as things stand :-

==================================

Now we make the only property we have the focus, by clicking in the 'Id' row (or horizontal), and then

using the PP to enter the new name of 'SpeakerId' - I prefer 'SpeakerID' but will go with Julia for this exercise.

Here is what I now have :-

=======================================================================================

We will now add some more string properties by clicking (left) in the Properties 'line' or row, and

then using the context menu options brought up with a right mouse click.

=================================================================================================================

Actually, with the 'Properties' (header) highlighted, pressing 'Ins' (insert) on the keyboard works OK as seen below :-

==============================

The PP has changed to look like that shown below, and I suspect we will use this for the other changes required.

Here is how mine looks (before I make any of Julia's changes) :-

========================================================

In fact while following through JL's instructions I have found that we can click anywhere in the

Properties header or sub-items to bring up context menu - see below :-

=======================================================================================================

There are a couple of small differences with what I have done and which JL recommends - see below that the

PP now only offers 'Max' and none for 'Max length', not 'True' as she has it written - check this out :-

======================================================================

So far so good, so lets make sure we don't click anything we shouldn't ;-)

Before doing the next part of this exercise I picked up with the mouse the 'Speaker' entity graphical image on

the designer surface and slid it to top left, out of the way of my new work to be carried out.

=========================================================================================

Now to add two more Entities - 'Session' and 'Track' - so we need to drag another Entity from the

Toolbox and drop it on the design surface :-

========================================================================

Lets change the Entity name another way - lets right click in the main header area and use

the Rename option from the context menu :-

=======================================================================

And once we succeed in changing the Entity name we can do the same for the 'Id' see below :-

=============================================================================

So we seem to be doing Okay for now ;-0)

Check this out with what you are doing :-

============================================================================

Adding the 'Track' entity - an important point to realise :

I tried adding the entity name 'Conference Track' as I thought that is what Julia had done from looking

at her schematic earlier in the text - see the result shown below :-

==================================================================================================

Yep! we may have expected this - no space allowed ;-)

Okay then, before we follow JL's advice to change a few properties, we need to see what we have - check this out below :-

=========================================================================================================

And here is a quick visual summary of the changes she suggests :-

==============================================================================================================================

Once again Julia likes the older, and probably safer, way which comes from not having VS11.

So here is her way shown below :-

========================================================================================================

And now we will try the interactive GUI designer way - I like Drag and Drop ! ;-)

Drag an Association from the Toolbox and take it into the 'ConferenceTrack' entity as shown in the next image :-

==========================================================================================================================================

Click in the ConferenceTrack (header or otherwise it would seem) and hold the mouse button down till you

move the pointer over into somewhere in the 'Session' entity graphic. Then release the mouse button.

You may need to try this a time or two _ BUT the great thing is that 'Ctrl + Z' does what it does best, and always!

Here is my hold and drag operation :-

========================================================================

And also we can see the result of my releasing the mouse button - check this out :-

=========================================================================

If we now click with the mouse over the association 'link' we see the following on out GUI surface :-

========================================================================

And having highlighted the 'Link' we see it has its properties available for viewing and changing

in the Properties Pane (PP) - see below :-

=========================================================

And now we need to set the situation at delete time, when a Conference Track gets deleted

Notice below that 'None' has been changed to 'Cascade'. Check this out :-

======================================================

I have had a reasonable play around with the Designer environment within VS11 and it would

appear that there are a few major changes from that used by Julia in VS 2010.

I will continue to try and use the GUI interactive stuff at all times, as it seems much improved.

We have probably done enough in this one subsection, so lets start another as we continue our development.

Move to the next subsection where we will make a 'Many-to Many' relationship.

See you there in a moment ...........................

PHH - 29th. August 2012.


Going futher with the 'CM' model

Our first 'Many-to-Many' relationship :

(Julia is on page 739 for your information, as you may be following along from her text.)

We will be using 'Speaker' and 'Session'.

If we try what Julia suggests, and right click in the Designer surface - the top RHS corner near 'Add New'

is where I clicked - then we get these context menus - see below :-

==========================================================================================

And choosing 'Association' brings up the following dialog screen :-

====================================================================

However, I think I will close that down and try the drag from the Toolbox, and will make my target the ;Session'

entity.

I may have not made this totally clear last time we did an Association, BUT, we need to click in the Toolbox (on the Association icon)

and then the cursor shape changes - at this point we are NOT dragging or holding down a mouse button.

We move the mouse to the first 'target' (here we need 'Session') and then click once - do not hold down the mouse button.

Lets give this a go now :-

=====================================================================================================

Note that the mouse cursor changes depending on where you are hovering, you can only click it when the red

warning is NOT showing - see below to see this 'warning' cursor :-

===================================================================================================

The active (or 'correct') cursor shape is shown when the cursor is anywhere in an 'Entity' graphic.

If you now make your second click in the 'Speaker' 'Entity' graphic then you see we get a new 'link' type

association graphical icon on our design surface. Here mine looks like the following image :-

=================================================================

Okay, as of yet this is NOT a 'many-to-Many', but we can soon put that right.

Don't Panic - if things goes Wrong ! :

Okay, I accept that for most of us we will need some practise at this interactive way of making a 'link' for an

'Association', so be aware that good old 'Ctrl+Z' works nicely on the Designer surface.

I have just done a test and my recently made (and correct) link has now completely gone. So I can have another

go at getting it right, and getting what I am after. Here goes.

With my now 're-made' association I will click and then hover over the 'link' graphice we have just made.

Hovering brings up a tooltip showing currently 'one to many' - see below :-

================================================================

But we also get a the Properties Pane (PP) showing the following - as long as we have clicked the graphic.

Here is what you should have at your end :-

=========================================================

Using mouse entry we can change this directly in the PP as we see in the next image :-

===================================================

The PP now changes to look like the following image :-

=========================================================

As well as the 'link' icon changing too - see below :-

============================================================

If we click the 'link' icon we get a slightly different image display see below for an example :-

================================================================

Here we see a bold font weight for only those 'NPs' involved, as well as the 'link' icon changing

just a little as well.

So if we click the other of the two 'link' icons we see our whole surface looking like this below :-

==========================================================================================================

Note the change to the bold fonts in the second and third Entities.

Time to move on ........

We now need to look at making an inheritance hierarchy.

See you in the next subsection .....................

PHH - 30th. August 2012.


Making an 'Inheritance Hierarchy'

Okay then guys, what is this all about ?

Well, its quite simple, we can have one 'Entity' inherit from another, mush as we do in our object coding.

Basically it is for similar reasons, many to do with not needing to re-type detail, as well as have detail re-used.

But we are not here to philosophize - we need to know how to 'make it all work' !

Before we can get into much detail we need a new and blank 'Entity' and we need to call this 'WorkShop'.

Lets make this now using the Toolbox :-

=======================================================

The result of this is as follows in the next image :-

===========================================================================

Okay then, lets move on to the other side of this activity / operation.

Well first of all lets look at the designer surface after a right mouse click to bring up the context menu :-

=================================================================================

However, we also see that there is an entry in the Toolbox for 'Inheritance' as well - see below :-

=================================================

And true to our promise, we will try and use the interactive GUI way to use the Designer.

After moving our entities around a little, and then selecting the 'Inheritance' tool, we see we get cursor 'shape'

feedback as we did earlier - see what we have part-way to the 'drop zone' as it were !

Check this out below :-

=============================================================================

Remember this is not a 'drag' operation, we make clear and clean 'clicks' at each stage. Maybe you will need

to do some practising, and don't forget 'Ctrl + Z' to get you out of trouble.

I have now moved the entities around to look like the smaller 'zoomed' image below :-

============================================================

We now need to rename the new Entity from 'Entity1' to 'WorkShop', as we see now :-

===============================

And now we wish to simply tell the designer 'system' that we wish our 'WorkShop' entity to inherit from 'Session'.

Lets try the toolbox and click on 'Inheritance' in the Toolbox list.

Below the cursor is over the target entity and we are ready to give another click of the mouse button :-

===========================================================================================================

=================================================================================================

Well, the results of my trials are as seen below, I guess it has worked OK !? - check this out :-

=================================================================

Notice the 'arrow' then the 'WorkShop' entry in the header of the 'Session' entity.

ERROR - Care - Warning !! ?? :

Okay you guys, it would appear that after checking Julia's results (of her work) we have done things the wrong

way around, but then we were learning, and trying out the GUI for the first time ;-)

Here is what Julia says we should be aiming at :-

=================================================

As you can see by the header of the 'WorkShop' entity ours is different. Now to see if we can repair things by first using 'Ctrl + Z'

to undo the previous actions. In fact we also see an Undo icon in the VS11 menu bar.

======================================================

I have tried clicking the Undo icon a time or two, and now have the following in my Design surface :-

======================================================================

So it would appear that we can do our Toolbox clicking once again - like a fresh approach - but this time

start at 'WorkShop' and then go to 'Session'.

Lets try this out now :-

=======================================================================

So far so good, now what do we get if we make our final click in the 'Session' graphical area ?

See below for my results at this end :-

=======================================================================

Well, at least it starts to look like what Julia was wanting us to achieve - we just need to get rid of

the extra 'Id' we seem to have. Lets do that now.

First we highlight the 'Id' property (check it shows in the PP) and then using the context menu options

(right click in the highlighted area) - see below :-

========================================================================

We can try first a 'Cut' choice, and then if that does not do it, the more drastic sounding 'Delete from Model'.

Fingers crossed, and don't forget we have 'Undo' ;-) The results of try 'Cut' are seen beneath :-

===============================================================

So comparing our graphic with Julia's Figure 25-11 we seem to have what is required, both in the

header detail as well as the arrowed 'link' line from 'WorkShop' to 'Session'. I notice she has lost the upper

case in her 'WorkShop' entity title !?

Don't worry about our ' + ' sign next to NPs in 'WorkShop' as when we clcik this is changes, and opens up

with no contents or sub-items - see below :-

================================================================

Finally on this section we should see what Julia says regarding making our EDM into a SQL database :-

======================================================================================================================

It now time to move on to the next subsection where we will try to make our DDL script from the EDM

Once we have an acceptable script (DDL ttype) we can run this in Management Studio and generate an instance

of our newly designed database.

See you in the next subsection .....................

PHH - 30th. August 2012.


Exploring the features of the Designer surface

PHH - 30th. August 2012.


DB schema - making it from our Model

We need to have an existing, but otherwise 'blank' database in our Management Studio 'shell'.

So lets make one now, this means that the wizard can then use / set-up the correct connection string

and the likes.

Lets just go with the flow for now - see my MS 'shell' as seen in the image below :-

==========================================================

This selection opens up the 'New database' dialog screen seen below :-

Here is a bit more detail - shown below :-

=======================================================================================

Above I am calling the new DB 'Conferences' as JL suggests.

Click OK at the bottom of the dialog form and it is done - you will see this in your MS 'shell' screen :-

========================================================

This image above shows a new and 'blank' DB apart from its name.

Now we can move on to the next stage - using the Wizard - that for Generating the DB schema from the Model.

Generating the DB from the 'Model' :

Click the mouse 'anywhere' on the 'Designer' surface - where there are not other items displayed?

In fact I have just tried it again, and we appear to be able to righ click even when the mouse pointer is

within the bounds of an entity - just be careful ;-)

This is what you should see :-

=======================================================

After clicking the appropriate menu option things whir for a little while.

======================================================================================

We can now make a new connection and look for our new 'blank' DB - here is what we need :-

==============================================================

The above image shows that we have selected the correct Server, the correct database, and then doing

a Test Connection - which is always a good idea ;-)

Now we will close the message box and click 'OK'.

In the following image we can see the results of what we have done - check it out :-

======================================================================================

After clicking 'Next' things whirl a little, and you may need to clcik your mouse pointer in the Solution Explorer

(SE) pane - it felt as if I had to, I tried clicking 'App.Config' and the Wizard screen returned - see below :-

Oh! I see, it was doing a lot of work finding the script for the DDL - see the next image :-

================================================================================================

And we can now scroll down and see that the whole DDL script is available for viewing.

Below I show the very bottom of the script I have generated at this end of things - check it out :-

================================================================================================

While having fun looking and scrolling, we must NOT lose sight of the fact that we are being offered a

chance to save the DDL file with a default name of 'CM_Model1.edmx.sql' - yes, it is a '.sql' file which

I usually call 'script files'.

Lets change the name to ' Conferences_Model1.edmx.sql ' and click finish.

===============================================================

One result of all this activity by ourselves and then the VS Designer facilities, is the following 'App.Config' entry :-

=================================================================================================================

Another is the DDL script itself. We will move on into the next subsection to see this.

See you there soon ..................

PHH - 30th. August 2012.


Studying the DLL script produced

As well as the App.Config content change we can see that in the SE we now have an

extra item shown below - and highlighted :-

=====================================================

When the auto generation takes place when we click 'Finish' the '.sql' file is

made from T-SQL (Transact SQL) script as I am using Microsoft SQL Server.

If you need to know more on T-SQL then look at 'ClickStartTSQL' on my web area. be warned though,

it is a huge area / topic in its own rights - not complicated or 'rocket science' just large and complex,

meaning it has lots of small parts to it.

This file is also opened in the editor, and the tab made active, so we view it immediately.

We see some of the script content in the following images :-

====================================================================

Here are a few other chosen parts as well :-

=========================================================================

===================================================================================================================

And now the 'FK' and Index stuff :-

===============================================================================================

Lets now move on to default values ..........

Details on Defaults - need to get thing straight in our heads :

What we are about to see (from Julia) may seen obvious BUT it needs to be said, thought about, and known.

Here is what she has to say :-

======================================================================================================================

If you need to know more of the underlying detail of what happened when we clicked 'Finish', then I suggest

you get hold of a copy of Julia's book - eBook version (in PDF) thoroughly recommended - see the Introduction section.

Lets now more on to actually making the database - or should I say filling out the 'blank' we already have ;-)

See you in the next subsection .....................

PHH - 30th. August 2012.


Making the DB from the Schema

DDL - 'Data Description Language' :

==========================

Basically, if we have a script file - of the standard '.sql' type we regularly use in our SQL use, all

we have to do is run it, or 'execute' it.

Now we hit the thorny, and RATHER important topic of 'security' ! Running any '.sql' file can do nasty

things to the wrong database, and even an incorrect script can do nasty things to the right one !

So all of us, you, me, and thee, need to take the uttermost precaution when we do run a script.

I am very used to running them from my MS (Management Studio) environment and so I will stick with

that approach. Julia has content in her book regarding this issue and you need to read it I feel.

Until you really know what you are doing I don't suggest running it from Visual Studio itself.

Since this is a learning exercise, and I can't do too much damage on this PC platform, then I will explore

and try out a few of the controls at the top of the T-SQL editor - these are special to this editor (only) !!

Lets take a look at what is present :-

===================================================================================================

But what are these ? we need a few images with tooltips showing perhaps !

On the other hand a right click in the editor surface shows us the context menu and therefore what is

likely to be on offer in the menu bar icons :- see below :-

==============================================================

=================================================================================

==========================================================================

===============================================================================

Both the Execute (before connection is made) and the 'Connect' icon in the menu bar bring

up the 'Connect to Server' dialog as shown below :-

=========================================================================

When I brought up the dialog, shown in above image, I had just clicked the 'Execute' icon.

This meant that as soon as I had clicked the 'Connect' button the T-SQL DLL script was run.

So quite soon I saw this in the editor surface :-

==========================================================

As well as the change in the editor menu bar as we can see in the following image :-

=================================================================================

And in fact we can see all the available DBs if we drop the list as shown next :-

====================================================================

Let us checkout one icon we did not earlier, that for 'New Query' - see below :-

=====================================================================

Time for a break - a nice cup of tea. When we return we will use Management Studio (MS) to see what we have

achieved, as well as how we can query from the VS11 shell environment.

Management Studio (MS) :

Having run the script from the VS11 environment it occurs to me that MS itself uses the VS 'shell' and so is in

many ways no different to using VS11 itself.

Once we look at MS and what we have achieved with the DDL t-SQL script file, we can revert to using many of the

facilities provided in VS11 itself.

Go to MS and use the context menu on the Tables node to Refresh the Tables list - check this out :-

==============================================================

Now looking at the Tables themselves we see the following :-

===========================================================

And looking at the Speakers table itself, we see more details as show below :-

================================================================

Okay then, we need to enter some data items and values, so we can do our testing in VS11.

Adding Data to the 'Conferences' new DB :

Right click the Speaker node in the Object Explorer 9OE) pane as seen below :-

=======================================================

This should bring up the Editor via which we can enter some information.

Note that the first column is greyed out and unavailable since the Server has control of it and the PK values entered.

====================================================================================================================================================

We seem to have enough to get us going in VS11, so lets move to the screen showing the VS shell.

If we move back to the T-SQL editor tab we can use the 'New Query' icon to bring up a new tab into which we can

type a SQL query statement - much as we do in MS itself.

Study the following image in which we get results returned as we do in MS :-

================================================================================================================

And if we then try to use a more suitable query, and not a VERY simple one, we can get this shown below :-

======================================================================

We need to realise that we now have to use T-SQL syntax and not .NET so take great CARE !!

Summary - so far :

Okay then, if we have to summarise so far it would be to say that much has been included in VS11, and

a lot of the basic (and useful) stuff for selecting Dbs for querying, and executing SQL queries if there for our use.

Personally, I like what MS guys have done, and will use VS whenever I can in place of switching over to MS.

Having said that, the new MS which comes with 'Denali' (MSSS 2012) is really nice too ;-0)

Unless I have gone blind it looks as though the EDM 'designer' surface is in VS11 but no equivalent in MS2012.

So I intend to give things a real good go and design some new DBs from within VS and miss out on MS and the

way I used to do things.

Time to move on .....................

See you in the next subsection

PHH - 30th. August 2012.


Chapter 9 -

Chapter 9 - Our Own Simple Start

Our Data :

Okay then guys, we have been led by Julia's experienced hand for too long and we need to try and

stand on our own two feet - lets be brave !

In trying out creating our own little application, from start to finish, we will see what we have learned and

what I may have forgotten, or missed in my first pass through all this stuff ;-)

I have found that I have a suitable little test DB called 'MyCompany' which I must have made for DevShare

'Olympic' 2012.

Let us try to attach this to an older version of SQL Server, the R2 2008 version - just to be different.

Our Application :

Since I have been doing WPF for years, I think I will make our simple project a WPF one, and follow the

data binding possibilities through from a simple start.

Querying with LINQ :

We will try to get some simple querying done with LINQ and have our results displayed in a suitable control.

However, we will also try to make a data input form where we can create new records and have them sent

back to the data source.

Getting Brave :

If we get success with the above goals, we may try something a bit more ambitious and on another Form select

customers (one by one) before completing an order and selecting products from a list.

It all depends on how tightly we keep our fingers crossed ;-0)

PHH - 1st. September 2012.


Getting our Database

Okay then guys, we need to find out database and attach it in Management Studio (MS) to a suitable

SQL Server, and one which is different to previous use in earlier chapters of these eNotes.

*** I will try and make this same simple DB available for download directly form these eNotes ***

For now here is my Windows Explorer view of my DB folder on my second drive 'D:'.

================================================================================================================================================

Before we can attach it to a SQL Server I need to open MS and choose a suitable Server.

As you can see in the next image we have a blank shell in MS and are choosing to open a connection - see below :-

=======================================================

Now in the following image we can see that instead of the MSSS 2012 instance of a Server, as previously used, we

are about to select the Developer version of 2008 R2, which I appropriately named so I could tell the difference.

Check this out :-

==========================================================================

And opening the connection we see the following within the MS shell :-

========================================================================================================================

And as you can see from the above image, we have no sign of 'MyCompany' as yet.

Right clicking the 'Databases' node we see the context menu to allow us to 'Attach'.

=================================================================

Navigate in the 'Locate DB Files' dialog to the '.mdf' you are wishing to use (hopefully you have done a download).

Here is what my dialog looks like :-

=================================================================

And this fills the input controls on the 'Attach DB' dialog like so - see below :-

================================================================================================

Okay guys, SQL is like this :(( I have failed to attach the DB to the older 2008 Server, but have no problems

at all with attaching it to the 'Denali' 2012 one. So much for a good idea.

Below is what my MS shell and environment looks like now - see below :-

================================================================================

I can't remember if I made the database in MSSS version 10 (2008 R2) or the latest version MSSS version 11.

Also I have not done enough testing to know if we should expect to be able to use it 'backwards' !

Lets just go with the flow and use things as they are.

Now we need to see which Tables are on offer to us for testing purposes - check this out below :-

=================================================

And we now need to checkout the column details - see below for that :-

======================================================

Okay, so far so good, but does this table have any data for us to use later ?

Lets try the useful context menu option 'Select Top 1000 Rows' :-

===========================================================

This does produce 23 rows of data, and some I can see is definitely demo and test stuff !!

Here is a snap-shot for your eyes :-

=============================================================================================

Yep! 'Pearly Gates' at 'Microsoft Place' sounds 'test data' to me ;-0))

While we are at it we may as well check to see we have Product entries too - see below :-

=====================================================================================================================================

Yes, plenty of 'Widget' stuff looks like a US test data table to me - I still can't place where it came from.

Where Next ? :

Well, that is a good question !

All we need to do now is start a new application - project - and then to point out Wizard at the file and path

we have researched above.

Lets get our sleeves rolled up.

PHH - 1st. September 2012.


Starting a GUI application

Lets get cracking right away.

Open VS11 with no solution open - or if one is, then close it down.

We will now start a new project of the WPF variety, so .NET 4 at least is required.

==================================================================================================

And when we get to choose from the templates we see we do as shown below :-

==========================================================================================================================

Notice we have called out new project / solution 'OurCompany'.

The OK button then produces entries in the Solution Explorer (SE) pane as follows :-

=========================================================================================================

The application compiles and runs - doesn't do much, and doesn't even look much - as yet !!

We now need to move to the next subsection where we address the issues of making our own EDM.

See you there .........................

PHH - 1st. September 2012.


Making a Simple EDM

Adding an EDM to our Project :

Now that we have an app, we need to add an item to it of type shown below - using the EDM template in the Data node.

Check this out below :-

====================================================================================================

And when the 'Add New Item' dialog appears make the entries you see in the following image :-

==========================================================================================================================

Since we have located our database already, we know we wish to generate our EDM from an existing DB, we don't

want an 'Empty' model - check this out below :-

======================================================================================

Now we need to use the Wizard dialogs to point to both our Server and our database so do something

at your end that suits where you have your files and what you server is called.

Below is what suits me here at this end of things :-

===============================================================

Don't forget to do a connection test, always a good idea !

In the Wizard dialog below, I have changed the name to what I think is appropriate 'EntityCustomer'

as we are only going to deal with the Customer table for now.

Look at the following details, and copy if needs be :-

========================================================================================

Now we need to be more selective - in the next 'Wizard' dialog select only the 'Customers' table.

Also change the Model Namespace as shown - to 'CustomerModel' :-

======================================================================================

Lets be brave and click Finish !

And now lets see what has happened in the SE pane - check this out below :-

================================================

We have a few more References as well as the EDM node(s).

Can you identify which References have been added ? It would be a good idea to find out I feel.

The easiest way to find out is to start an new 'TestRefs' app which is just WPF in nature, then compare.

Check this out below :-

===================================================

System.Security

System.Runtime.Serialization

System.Data.Entity

Eleven (11) versus fourteen (14), which means we have three (3) extras.

Note that the LINQ reference is in there as a standard WPF entry - interesting !?

Moving On :

Well then, what was the results shown on screen for the Model designer surface, what is the

diagram like ? - see below what I have :-

==============================================================================

In the work we did above you may have noticed that 'unfortunately' I had named the data Table 'Customers',

and that as we know cuts across the naming the Entity Model 'system' needs to use when we let it have its head.

See below for the EDM naming scheme, and remember this is quite separate to the Table naming - there is not

a problem, the Table is still named 'Customers' which I don't usually do - the plural that is :-

===============================================

Lets now look at the partly collapsed code which has been generated - see below :-

=============================================================================================

In the above image notice that we have just one 'Entity' in the Entities region.

Also the name of the 'ObjectContext' type we need to use in LINQ queries is "EntityCustomer".

Moving On - getting visual :

Okay you guys, enough success for any one subsection, lets go to the next one - see you there !

In the next section we will checkout that we can send simple queries using our EDM and 'ObjectContent'

called "EntityCustomer".

PHH - 1st. September 2012.

Addendum :

Before we move on we ought to see what the connection string data is that was placed in the App.Config file so

checkout the details shown below :-

================================================================================================================================================

This should tie up with what we entered into the Wizard dialog screens.

PHH.


Testing with a simple Query

Now before we rush off to try and get some data binding on our WPF form, we do need to see

if we have gotten everything else in place, all that we need to be able to query the Model and

get back suitable data items.

Making a Simple Test :

In order to see that we have gotten our EDM stuff correct, we need to use the new 'EntityCustomer' class to see

if we can pull any data back from our data source.

Only if we get success with some simple querying will it make sense to move on to try and get data binding up and running,

in some shape or form.

Here goes with a simple test, directly from the Form constructor.

You will notice that this is just like the simple querying we did in earlier chapters of these eNotes - check it out :-

==========================================================================================================================

Note that in the above code example we can use 'MessageBox' in place of the Console as we have it available to us via

the references and namespaces we already have in place.

Well, that's great ! We seem to have things working nicely.

So motivated by success we can tidy this code up, make a method for the testing, and also improve our query.

Checkout the following :-

==================================================================================================================================

Fine, now what we need to do is grab the returned data and put it into a permanent List of our own.

We can then use this for our first simple attempt at binding to our WPF Form controls.

Grabbing a Permanent List of Items :

Remember, that Julia told us that each time we 'use' the query variable the LINQ system causes the query to be run

against the data source, well we need to address this problem / issue, right now.

Here first is the result of using our new List - see below and study carefully :-

============================================================================================================

And to go along with this we need to see the method called 'GrabOutCustomerList', so here it is shown

in the following image - check it out carefully :-

=====================================================================================

So this means we ought to be able to use the List with our own WPF control binding.

But before we do that we need to see what the easy way does for us ;-) Drag and Drop.

We will study the data connectivity with GUI elements in the next section.

See you there ..........................

PHH - 1st. September 2012.


Connecting Data with GUI

Here is the Good part :

[ .. I think it may be a good time for you to 'Build' your app - I think I got caught out because I neglected to do so !? .. ]

When we open up the XAML designer surface we see the following set of details.

Note that the Data Sources pane has been filled with our only Entity, if that's what we ought to call it.

=================================================================================================================================================

*** Remember *** to build the app, don't run it as yet.

In the next image we see that the default 'DataGrid' setting is showing for my designer surface.

Check yours out and select the same as me - the DataGrid :-

============================================

Once you have the correct setting, drag from the Toolbox a 'Customers' item into the body of the WPF form.

Mine looks like this :-

==================================================================================================================

When you let the drag event complete - by 'dropping' - you will get a control which needs to be resized and placed on the

form. When you have the correct mouse cursor symbol drag the side of the control so the dock at the edges of the form itself.

Here is what I have on mine - see below :-

===================================================================================================================

You may even see that he grid column headers match up with the property names of our 'entity' thingy !

Well, if you did not get the error box that I first did (and I am not sure what I did to clear it, it can't be much) then you

too should see something similar to that above in the image.

And it takes very little effort to build and run the app with 'F5'.

I have just done this and 'bingo' we have a whole pile of data - check this out below :-

===============================================================================================================

You will notice when you scan the data above, that all of it appears to be present - and that is correct.

This has nothing to do with our earlier filtered query, and the data collection we got returned and placed permanently

in our list object.

After a little tidying in the editor we can see the code that the VS system made when we did our drag and drop, then

control re-sizing etc..

Check this out carefully - and don't panic if you are not a XAML guys as yet ;-)

=====================================================================================================================================================================================

And for those guys that like to know everything, and be totally in control, here is the code that was added to the

'MainWindow' partial class file that the WPF template made originally.

======================================================================================================================================

Yes, I tidied this as well, to make it easier to read - nothing much however.

I particularly draw your attention to line 82 and 83 below, in which the association is made which effectively handles the

data binding.

==========================================================================================================

Okay, nice and easy, the VS11 system does a lot for us - BUT - we can now show we are still partly in charge, and do

some of our own binding ;-)

Go back to displaying the XAML design surface, place the DataGrid in focus by clicking in the XAML script within the text editor.

Once this is correctly in focus, use the top 'handle' to drag the top of the DataGrid control down to leave some room on the form.

This is what I have - see below :-

=================================================================================

Now slide from the toolbox a 'ComboBox' control and place and re-size into the top available 'space'.

====================================================================================================================

On line 34 I have added the 'Name' attribute as well as it value of 'OurCustomerCombo'.

Build and run it just to see we are on the right course - see below for my output here :-

=================================================================================

Yep, as well suspected, a nice drop list control but no data as yet.

Lets put that right with just a couple of lines of code.

====================================================================================================================

First we need to handle the binding, so in the above script we add the attribute shown on line 34 - 'ItemsSource'.

To go along with this - the other end of the binding 'link' so to speak, we need the line of code shown below - line 29.

Check this out :-

=============================================================================

Yep! all we are doing is binding our returned list from our method entitled 'GrabOurCustomerList', to

the ComboBox.

See below for the proof that we have 13 list items - we can deal with the data template in just a moment.

[ .. Check with the last subsection to see that our filter query produces 13 return items. ]

============================================================================================

So the above is proof of success -) Okay, I know, you guys new to WPF will think things have gone

horribly wrong - BUT - you will see that all we need is a 'DataTemplate' defining in our XAML script.

Now then, where is my ClickStart eNotes for such a template - even my METRO ones should show that.

No, as it happens I went to the XAML eNotes and found what I wanted - the results are good enough for a start

I feel so give them the once over, see below :-

====================================================================================================

Okay, I know, not all of the data properties / fields are included as yet, AND, we could do a lot to improve

the layout - but 'hey!' we do have data, and it is bound, and it also comes from our LINQ query with a filter

condition, and is therefore using our 'Entity' stuff.

Oh! sorry, nearly forgot, we have to show and study the script for the 'DataTemplate' - so here it is below :-

=========================================================================================================================

Lines 32 through 44 have been added, but please realise that we could have put the template script into the Resources

section in order to clean up the script layout a little.

However, we are here to study and learn EF4 and not fiddle around with WPF layout aspects.

But just for a quick bit of fun, lets make the 'LastName' bold and the 'City' italic, and the 'Address' blue in colour ;-)

Oh! I told you we should not start messing around, this stuff is just too easy and also great fun ;-0))

Check this out as we pass on to the next subsection :-

=========================================================================================

The XAML script changes are seen in the next image - not too much trouble :-

=========================================================================================

See you in the next section ....................

PHH - 1st. September 2012.


Multiple EDMs

Okay guys, a new day and a new challenge !

Today I wish to explore the topic area of 'Multiple EDMs'. As yet I know little about the subject.

However, it appeared from work I was following through previously, that we could create multiple EDMs

and so we must be able to make that situation work for us - and am possibly thinking ahead to MVVM !

Since we have already got a simple EDM which deals simply with a Customer 'Entity', let us make another

one which deals with Tables in our 'MyCompany' database related to orders and products.

To remind ourselves of those tables available to us, lets see our Object Explorer pane in Management Studio :-

=============================================================

The above image shows 'Customers' through to 'ProductTypes' for our use, the others are test and demo 'things'.

Making a Second EDM :

Okay then, all we have to do is highlight the project 'OurCompany' in the Solution Explorer (SE) pane, and then use

the context menu to 'Add' a 'New Item' - see below :-

==============================================================================================

When the 'Add New Item' dialog screen is presented to you select the Data node in the C# list on the left,

and then the template for 'ADN.NET Entity Data Model'.

Supply a better name than the default offered, I chose 'OrderProductModel.edmx' - see below :-

=============================================================================================================

When you get the Wizard on screen choose the icon option 'Generate from database' - see below :-

=====================================================================

Okay - so far, so good ! Now a bit I have been waiting to do - select a 'Data Connection' we already have !

Since we made a Data Connection for the same database, for the previous EDM creation, we should still have

it in the drop list - so lets have a look :-

==========================================================================================================

Yes, there it is, second in my list, so I will now select it - lets see what happens :-

===============================================================================================

Okay then, a couple things to notice, and get right etc..

Firstly the drop list selection now has correctly filled the 'Entity connection string' text block, and also that

I have purposefully unchecked the 'Save ....... ' check-box.

Since we already have the correct connection string in our 'App.Config' file we don't need do anything concerning

it, this time around.

*** WARNING *** this is not what I thought - causes disasters - read the child section of this one.

The subsection is entitled 'Multiple connection string'.

So we can click 'Next' to move on with the Wizard - see below :-

================================================================================================

Notice that, in the image shown above, we have not selected 'ProductTypes' simply for demonstration purposes.

We can make a third EDM for 'Products' later, when we will choose both product related tables.

So we have selected the three tables, and no 'views' or 'SProcs'.

The EDM name is set to be 'OrderProductModel' - lets click 'Finish' to see what happens.

==================================================================================================

The above details looks just what we would expect - well I am happy enough.

Now then, what else has happened behind the scenes when we clicked 'Finish' in the Wizard ?

Lets use the tab (or double click in the SE pane) to open and bring to focus, the 'MainWindow' XAML

designer, next to which I have the 'Data Sources' pane - see below :-

[ .. this shows Entity Container names ..]

====================================================================

Now I suspect all we needed to do was view the 'Data Sources' (DS) pane, whether we opened the XAML

designer / editor or not !

However, we can see in my DS pane - next to my 'MainWindow' WPF form - that we now have some extra

items included within it.

Unfortunately we seem to have 'Entities' as a node entry, and we have missed a chance (somewhere in the

Wizard use) to change the name to something more suitable, say 'EntityOrderProduct'.

This node item, or entry, is actually an Enity Container name.

I wonder if we can rename this using the SE pane and the context menu, without screwing things up ?!

Lets give it a try shall we ?

First of all we need to see what is in the SE pane 'as of now' :-

====================================================

And if we right click in this leaf node we see the available menu options to be :-

===========================================================================================

And above we see that 'Rename' is there for us to select, its not greyed out.

So lets go for it :-

[ *** care *** the following is not what I would like it to be !? ]

============================================================================================================

Although we can rename the SE item as seen above - this is in fact NOT the way to do what we are after !!!

We need to rename the 'Entity Container' itself, by first right clicking in the designer surface of the EDM we wish

to change (remember to get the correct one when we have multiple EDMs) - here I am bringing up the context menu :-

========================================================================================

Once we select 'Properties' as seen above, we get something we can work with ;-0)

In the following image we see an editable property (attribute) of the Entity Model itself :-

============================================================================

So I have changed this to something more suitable to my tastes and liking ;-)

Check this out below :-

============================================================================

So, now the BIG worry, does this change all the necessary places in our project and solution ?

Well, if we return to the DS pane (Data Sources) next to my MainWindow XAML designer, we see

the following details :-

===============================================================================

As you can see the change seems to have affected what we had first wished, and also that there

is no context menu way of doing a 'Rename' procedure.

So what does the SE pane look like ? We have now three Data Source entries and one I think is

'Extra' or superfluous to requirements - lets try and remove it - see the following details :-

================================================================================================================================

And after crossing my fingers and clicking 'OK' we seem to have the following :-

=============================================================

Yep, just the two we were after !

Now a rebuild, compile, and run will see if we have done most things OK - lets do it.

Yes, my main WPF form shows all the data items in grid and drop list.

Okay then guys, time to move on. After a fresh coffee I will start into the next subsection in which we will

see how to have many (multiple) WPF forms, with each using different EDMs.

See you in the next subsection .................

PHH - 1st. September 2012.


Multiple connection strings

We need to be very careful with connections string, until we get a lot more experience with EDM.

I have just given myself grief and taken some time and fiddling about to realise it, then put it right.

If we look at the contents of the 'App.Config' file after we made the first EDM we see the (rearranged line

details) look like the following :-

================================================================================================================================================

Notice that the whole string has been 'Added' into a 'connectionStrings' collection - by the look of things.

The 'Name' attribute of this long entry item is "EntityCustomer" and it was made by the Wizard and automatic VS11 system

when we were making our first Entity container called 'EntityCustomer.

Therefore it is not too difficult to work out that we will need an entry - with suitable / appropriate 'Names' for each separate

Entity container we add afterwards.

I have just conducted a test or experiment, and have added two extra Entity containers (via new EDMs) and these are seen

in the following image - check this out below :-

===========================================

Since I actually did checked the 'Save' check-box, as seen below :-

===================================================

We have now got three connection string entries in App.Config file, one for each.

The following image shows the auto-added code after I have tidied it, but the contents was placed there by the VS system.

Take a careful look at this XAML script :-

===================================================================================================================================================

So for me, and my exploration of the EF4 possibilities in VS11, I think I will eave it to the system in future.

By this I also mean that I will check the 'Save' check-box.

If you do get it wrong, and the Query you end up using (somewhere) needs a string which is not there, or not

found, an 'Access Violation' message is got in the debugger output panes. Not very obvious, and the app just

'bombs out' as they used to say in olden days of programming ;-)

So you have been warned !!!

Time to move on ..............

PHH - 2nd. September 2012.


Tidying the SE pane

Now that I have had time to explore the EF4 system a little, and also to try out where we may

be going next with multiple WPF forms, I think we should tidy up out solution 'structure' within

the SE pane.

*** Be Careful ! ***

A word of warning, it is all too easy to set out with the intention of tidying and structuring the SE pane,

and very soon have a solution which does not run, and you are unable to put things back to rights :((

I know that we have ALL done such things ;-)

So remember to back backup copies of your solution if you are going to be messing around, sorry,

tidying !!

Where are we going ? :

Well, it is easy enough for you to show me what I have working here, and what the structure looks like.

So study the following image VERY carefully, and see how it differs from what you have at your end :-

====================================================================================================================

The above images show that I have added two folder 'nodes' to the 'OurCompany' project.

The plan is, that apart from 'MainWindow' we should have all our other WPF forms in a folder named 'OtherWPFforms',

and any 'Models' we create in a folder named 'OurModels'.

'Drag and Drop' or start again !? :

Well, this is where I warn you to be careful ;-)

I tried Dragging the 'Models' into the new folders, and of course broke the application. This can be fixed with some code

changes, and I will now attempt to guide you on this.

If what we discuss next 'fails' then you will have to start again after deleting the Project and put the folders in right from

the very start of things.

However, all of this is good practise for you, so don't worry. Its often stuff like this that teaches us the most.

The first thing which is worth doing, after you have made the new folders, is to add two code lines to the top of each

of the 'NET (or other) PRG files - as seen below :-

==========================================================

This makes sure the compiler can find our classes in the new folders.

Now on to the more drastic work / stuff .............

Delete / remove, and Tidy :

Go to your Data Sources (DS) pane and check that the entries there fit two sections of the SE pane.

First lets see what my DS pane looks like, and it is different, as I have been experimenting at this end since

recording earlier eNotes subsections.

==========================================

The first - and important - SE sub-folder to check out is the 'DataSources' one within the 'Properties' node in SE.

After quite a bit of old file 'deletion' mine now looks like this below :-

======================================================================

Notice that the actual item entries have suitable names, showing that I made them after the new folders were

in existence, and being used for making new EDMs etc..

Another SE folder to check out is the 'OurModels' folder (node).

This should match up with the others we have shown so far - see what mine looks like, set out below :-

=====================================================

And after you have done this work of checking the pane structure, and tidying that, you should try examining the

code in the 'MainWindow' section - where the event handler and 'ObjectQuery' code was placed by the VS system.

Any issues you have will all be to do with Namespaces, so be careful and make one change at a time, then test

and check, or whatever you think is necessary.

This is how mine looks now -see below :-

====================================================================================================================================

Conveniently, shown above, the image may indicate with green side bar icons, just which lines I have edited this current session.

Some of my changes were to simplify the long names since I have added the 'using' statements at the top of my PRG file.

You may need to 'Rebuild' to totally remove any red squiggly lines - one or two seem to stay even when the code is correct but,

rebuilding puts things right.

Rebuild and Run :

Now, if you are feeling brave you should do a 'rebuild' and then run the app - see below for my results :-

==================================================================================

Yes, I know, I have multiple forms, but I did warn you that I had been experimenting.

Let us now move on to the next subsection where we can see how to have multiple forms working together,

as well as each form using different EDMs and DataSource objects / classes.

Commiserations !? :

If nothing works for you, and after some careful thought you come to the conclusion that you have broken the

app so much that you and it will never recover, then be bold, delete the project and start again.

But this time place the folders within the SE structure right at the start of things.

See you in the next subsection ......................

PHH - 3rd. September 2012.

Addendum :

I have to say that one annoying aspect of the VS / Template behaviour is that the connection strings in the App.Config

file are always remade with no line breaks - so we get a VERY long and unreadable single line - see below :-

=================================================================================================================================================================================

When we do some tidying / white space editing, we see that we have FIVE connection string sections, three

hanging around from earlier attempts and tries :(

Oh! it looks as though we must take control after the Template system tries to help us!!

Anyway, here is an image of what I have here, after tidying up :-

======================================================================================================================================================================================

In the above detail you can see the names of the other connection strings are for 'EntityOrder', 'EntityOrderProd', and also 'ProductEntity'.

I have a feeling that it may be as good an idea as any to allow the Template to supply default value to names of new EDMs and containers.

We shall see in time, when we build up a style of coding with which we feel comfortable.


Multiple GUI forms

Setting things up for later :

If we are going to explore having multiple (or many) WPF forms, then we need a simple way to navigate to them.

I suggest we add push buttons to the main form, so that we can use their 'Click' event to launch our other forms,

those yet to be made ;-)

Go to your 'MainWindow' designer surface and move the grid and drop list controls so to leave room on the form,

at the top, for some Buttons - checkout what I have done here :-

=========================================================================

After dragging a Button from the Toolbox, change the XAML script to look like this shown below :-

=====================================================================================================================

Its looking good, now we need to be able to respond to the click of the mouse on the Button .........

Responding to an Event :

To make things easy for working on the designer surface, increase the zoom size of the graphics to 100%.

Now move the mouse pointer inside the Button area and double click it :-

==================================================

This cause two things to happen.

The first obvious one is that we are left focused in the C# code tab for the main form ('MainWindow') as

seen below :-

==================================================================================================

This provides a blank 'stub' for us to add code to later, when we have another form which to navigate.

The second we see if we type 'Ctrl, - ' { said, control and minus }, as this takes us back to where we

have come from, and so we are placed back in the XAML script editor - see below :-

======================================================================================================================================

The yellow side bar shows where unsaved script lines have been edited.

Line 48, at the extreme LHS (left hand side) shows the addition of a new event (attribute?), that for 'Click'.

The default name for the event handler is the value of the name attribute with '_Click' added to the LHS.

There are other ways to add events, but the double click on many controls is sufficient, simply because the most commonly

used event for that type of control is added for us.

Compile and Run :

Lets see what we have, and also if we have any compile errors.

Press F5 to see what happens - here we go ...........

=========================================================================

Sorry! - not very colourful as yet, BUT, it seems to work OK, apart from the Button click, which of course

does nothing at all, as yet ;-)

Lets move on ..........

Making the Second WPF Form :

Okay guys, we now need a second form, so that we can launch it from our Button click.

We need another WPF form t handle our 'Orders and Products' data presentations.

lets collapse the nodes in the SE pane to look like this below :-

=============================================================

Then using the context menu of the 'OurCompany' node, choose to add a new 'Window' item as shown below :-

===================================================================================

This choice brings up the templates dialog screen as seen below :-

=============================================================================================================

Notice that we have called the new form 'OrdersAndProducts'.

After pressing 'Add' we get a new XAML designer surface - that for the 'OrdersAndProducts' form.

Check this out for yourself :-

==============================================================================================

Okay then, yes, I know we have a long way to go to make it as we may wish - BUT we can at least make the

Button launch our new form, from that Button e just placed on the 'MainWindow' form.

First of all lets change the title for our second Window (form) as seen below in the XAML script editor :-

=====================================================================================================

Check your SE pane to see you have the new entry for 'OrdsAndProds' - mine is like this :-

===============================================

Now lets move on to handling the click event ................

Adding the Event Handler Code :

Return to the so far empty 'stub' in the C# code of 'MainWindow', and add two short lines like those

shown in the image below :-

================================================================================================

Now you have added these couple of lines of code, compile and run the app., then click the new button

and if you are doing well you will see this shown below :-

==================================================================================

Okay, I did resize the second form by dragging the sides and bottom edge.

Lets move on a pace ..................

Adding the Form Controls to 'Orders And Products' :

We need to enlarge the new form, set the width and height in the XAML editor as seen below :-

====================================================================================================

Notice I set the Zoom factor to 50% for ease of display in the image above.

Reset it to 100% before we do any dragging of tools or Data Source icons.

Navigate to the XAML designer surface for 'OaP' (OrdersAndProducts).

Change the default icon on 'Details' to the 'ListBox' icon as seen below :-

========================================

Now click the Orders node and drag a copy of it onto the form and then release the mouse button.

Here is what I got showing on the design surface :-

=============================================================================================

*** WARNING *** Once again (it happened earlier in this section) I had trouble with my first attempts at

dragging from the DS pane.

I first tried the 'List' icon an dragged that, but nothing seemed to happen, so I tried to drag once more.

That was a mistake as all that seemed to happen was that I got two lots of auto-added code in the

Window Load event handler. Which I had to edit manually - highlight and 'chop' using delete!

===========================================================================

The extra code added by the VS 'system' to support the 'details' of the Order DS is shown below :-

[ .. ** Note ** I have cleaned up the code by removing long namespaces and adding the suitable }

[ lines in the 'using' section ..]

================================================================================================================================================

And now, if we are feeling brave, we can try a rebuild, compile and run - use 'F5' and see this below (I hope) :-

==================================================================================

As you can see, we have a second screen - which is displaying an order, and I suspect the first one of the collection

returned by the ADO.NET query underneath our code - that used by the EF4 system.

Time to move on after that success, lets go into the subsection which follows, and see how to navigate the items in

the collection.

See you in the next subsection ........................

PHH - 2nd. September 2012.

Addendum :

With our new 'Folder' structure my SE contents looks like this below :-

==========================================================================


Getting 'binding' stuff to work

Okay you guys, lets now take some control of things, make things happen for ourselves, not just letting

the VS 'shell' and its Templates do things behind the scenes - even if they are a little magic ;-)

Lets do some work on the second form, the one called 'Orders And Products'.

We will do some work to aid 'Navigation', and by this I mean we will be able to move through the Order items

and not just forward, but back the other way as well.

Navigating - the Items :

First we need a couple of Button controls on our form.

Bring this into focus so that we see the WPF / XAML designer surface, then slide a Button out from

the Toolbox and place it on the form as I have just done - see below :-

======================================================================================================

If you get things right you will see the following :-

=====================================================================

Now slide a second button onto the designer surface and place it beneath the first one - like so :-

================================================

Remember to use the Zoom function to make your placement easier for you - go in an out with the zoom,

as you need to work on the graphics and then on the XAML script - this can maximise your working space to

good effect.

Now use the XAML editor to change the text on the Button surfaces as shown in the next image :-

========================================================================================================

Okay so far, now for some interactivity ..........

Events and Handlers :

Lets use the easy way to get some events and handler stubs placed in code and script by the XAML designer.

However, before we get into events, lets name our Buttons, to make reading code easier as we progress. Normally,

naming XAML controls and elements is not really necessary as we should be using data binding and MVVM in

such a way as to make it unnecessary, or even undesirable.

Here is what I just did to name our two Buttons :-

================================================================================================

Double click the Button surface of both Buttons in turn - remember 'Ctrl, -' {said control plus minus}, will take

you back to where you were last, the XAML designer. this is needed because the VS system places us in the code

after we do our first double click.

Now that we have named our Buttons, the auto event 'double click' action gives us a named 'Click' event as well.

Checkout the following :-

===============================================================================================================

Lets now move on .............

Moving on - getting our code correct :

If we now go to the tab which holds the code .prg for our new form ( 'OrdersAndProducts.xaml.cs' ), we see a couple

of important things.

First of all we have two empty stubs for our event handling code to go into, but also on line 41 we see we have had set

by the VS system - when we dragged the Data Source onto the form surface - a 'ViewSource' object.

This is what is displaying in any bound control, or sets of controls, depending on which icon we selected before the drag drop.

WE will use the 'View' property of this to populate our blank stubs - first, checkout the code we have to start with :-

==========================================================================================================

Before we code some content into our event 'stubs', lets us explore the intellisense drop option lists - we

can copy part of line 41 to help us do this - no, sorry, intellisense works on line 42 below, but not on 47 with

a part copied line, for some reason :-

=================================================================================================================================================

and when we select 'View' we see the following drop list :-

=========================================================================================================================================================================

We ought to have realised that if the intellisense system does not 'kick into action' like when tried above,

that we probably have a 'scoping' issue.

We need to make a 'CollectionViewSource' object which has wider scope, that of the whole form class would be OK.

Okay then folks, lets make the few changes we need to do this - see below :-

==================================================================

===============================================================================================================

The two above changes to our C# code mean that we are now able to get intellisense on our new object - see below :-

==========================================================================================================================================

So if we complete our two lines we need to add, one into each of the empty event handler 'stubs' we get the

following code which the designer / parser / compiler does no complain over ;-0)

=====================================================================================

As you can see, we are trying to move back and forth through the collection, with our two buttons to help us.

Lets try it for real ..............

Trying Out the Navigation :

When we launch the app., we need to then click the 'Orders and Products' button, to get the second screen.

When this came up I clicked next till I got to the last item in the collection - as seen below :-

=======================================================================

The only reason I know this is the last one is because I clicked again, and got a blank set of input boxes.

To return to the last item I then clicked 'Previous'.

It strongly looks to me as though we can enter a new order in this way, however, we would also need an

event and handler to save any new changes we make to items in the collection.

Also, it may be much easier to explore adding new items with a DataGrid control in place of TextBoxes etc..

Plenty of time to find out, we can come to changes soon, first some more navigation.

Adding More Navigation Controls :

Okay, lets have some fun, here is what I now have - checkout below :-

==============================================================

As you can see we have four extra buttons with symbols marked similar to those commonly

used for navigation through collections and lists.

I have to warn you now that I am just going to use some standard events and event association handling,

not any fancy binding technique ;-)

All I am wishing to do is show that we can use the collection 'view' object to move through the items in the

collection via the standard members provided.

Oh! and have a bit of fun with the scroll bar or slider control as well !

Study the image below which has a scroll bar working nicely, BUT, I should have used a

'Slider' control, so I will change this - both work OK :-

=====================================================

And now the 'Slider' :-

========================================================

Although I had the scroll bar working just as well as the slider now is, we ought to use the 'Slider'

control because that is what it is designed for - just what we are doing.

Now let us see the XAML script which gives us the five new controls as well as the events required :-

================================================================================================================

Now we can study the event handler methods as well as the 'SetSlider' method which is required when

we use any of the four navigation buttons. In order to keep the slider in-line with the position set by the buttons,

we need to reset the slider each time a button is clicked.

Checkout the following code, it is really quite simple :-

==========================================================================================================================

Another time, another, place, another day .......... I will look at using data binding - BUT - for now

we must focus on 'Entity' related stuff, that is our overall task ;-)

Also, another task which needs addressing on this form, is that for adding a new item, that is more

pressing as it is part of what we are 'all about' in these eNotes.

PHH - 3rd. September 2012.


Making changes 'Stick'

If you have worked with databases much previous to this, and in particular SQL Table DBs, you

will know what a tedious thing it can be to code an application such that we save changes back to the

data tables.

However, with EF4 the news is good, and we can do this quite easily, as well as NOT having to worry

ourselves with the details of 'dirty' cells and the like.

Take a look at the following image, it is based on what we just did in the last subsection, and has an extra

button for the newly required 'action' of "saving".

Check this out below :-

===================================================================================

In the above image I have shown the screen after I have changed three fields, the date, as well as Tax

and Shipping.

I have added a message box in the code shown below, just to see if things are joined / connected, in my code.

Checkout the line 81 which does the difficult stuff in one easy go - one line much power and flexibility ;-)

================================================================================================

It was also useful to be able to hear my local drive kick into action when the SQL Server was being queried - there

had been a period of inactivity before that while I wrote some eNotes and made some code changes.

However, you need proof, so here it is from the MS shell surface :-

===========================================================================================================================

Now if I promise you to go in and use our application a second time and this time I will change two records (items)

before I click the 'Save' button (only once).

We will go and see if row two and four can be changed, or should I say 'OrderID' 2 and 4, and we will make the figures

2.22 and 5.55 as well as 4.44 and 9.99 - lets see what happens.

Fingers crossed :-

[ .. In fact I used 5.555 and 9.999 in the Shipping fields .. ]

Now checkout the following couple of images to see what has happened :-

============================================================================

I visited two Orders, made two sets of changes, and saved only once.

Lets now re-execute the query we had in MS and see what data is returned into the data grid.

Checkout the following details :-

================================================================================================================

Yep! it seems to me that ALL the changes I made on the two records, have been persisted to the back-end data source.

Great stuff !!!

Now then, lets try and 'break it' "MythBusters" style ;-) Do you watch 'MythBusters' on the TV ?

I will now try and change the value of the 'Primary Key', lets try and change 13 to 31 and see what happens.

============================================================================

And after I click the 'Save' button eventually I got this complaint from the debugger.

Although we need to trap this, or handle it in some nicer way, at least the basic underlying system does

NOT screw things up ;-) Nice to know !

=======================================================================================================================================

Lets try another "Jamie" 'MythBuster' trick, changing the 'Customer ID' to a non-existing value !

=================================================================================================

=======================================================================================

==================================================================================================================

==============================================================================

Creating a New Record - then Saving to Back-end :

After using the 'Orders And Products' WPF form for some exploratory work, it is tempting to think

that if we use the navigation buttons to move past the end of the collection, that we can simply

enter new data details and then force a 'Save Changes' in the way we did for the Customers screen.

=================================================================================

When we do this we do not get any error message, but equally we do not get any data showing

up in management Studio either :(

========================================================================

It would appear to me that we need to make sure we get an extra item into the collection, then

make input changes, and then 'Save' would function correctly.

If the 'DataGrid' control can do this automatically with the same sort of collection then we ought to

be able to 'force the issue' I feel.

After some time messing about, trialing and testing, and getting VERY frustrated, I think I have cracked it !?

One Way to Add on Item via 'LINQ to Entities' :

I have found the 'spark' I needed to get my mind going in the right direction, in the eBook by 'Pialorsi & Russo'.

Thanks guys ;-)

The syntax of the code for adding an extra (new) item to the collection is as follows :-

================================================================================

And this code relies on the following couple of lines :-

===================================================================================

Basically the above code reads as :-

... add to the 'context' object made from the 'Entity Set' called 'EntiesOrderProduct', the object

'oOrd' and place it in the 'Orders' collection within that set.

Obviously, we can also do similarly to create new 'OrderItem' and 'Product' items in their respective

collections, as these too are in the 'Entity Set'.

To remind us of the situation checkout this following image :-

===============================

Okay then guys, lets see what I got with my first positive test, even though the code needs to be

changed and improved- nothing like a bit of success to motivate us ;-)

Check this out, although the data details will prove irrelevant until we make some code changes :-

=========================================================================================

Now then, we got no error messages, but before we examine the back-end data using Management

Studio, we need to see the code that was run when we clicked the 'Create New' button - see below :-

==============================================================================================

As you can see in the above image, we have just made a pretty random sort of new Order object, and

then once we have it we are passing it into the 'AddObject' method.

It is lines 106 and 107 which do the interesting bits.

And now for a look at the data as it is at this very moment - checkout the following image :-

================================================================

Okay then guys, which eagle eyed person noticed that I must have tried the 'Create New' button

more than once. In fact we can see that there was 16 minutes between my pressing (or clicking).

What we do also notice is that any value for the Primary Key (PK) is ignored by the Server and the

next correct value supplied by the system.

Moving on, we now need to connect up the GUI controls and also change the code to use values

from the input boxes of the WPF form.

The following new code lines seem to work just fine, yes, I know they are not very secure yet, and would

allow re-entry from exiting record items - BUT - one thing at a time ;-)

Check them out as they are at the moment, and as seen below :-

=============================================================================================================

And when we compile and run we see this - but note I used the GUI controls to move past the end of the

collection, by going to the end with the slider, and then clicking the 'Next' symbol Button.

Once we had the blank fields for the 'last plus one' item, I entered details as shown :-

====================================================================================================

Obviously, we now need to check the back-end data with MS to see what has happened - see below :-

================================================================

Yep! it looks good to me - BUT - one minor point is that we are just getting the Date and no Time

it would seem. I will leave that for you to sort out, as it is a minor side issues really.

Tighter control of Data Entry :

===============================================================================================

=========================================================================================

====================================================================================================================

================================================================================================================================================================

======================================================================================================================================

Seeing the New Item :

=============================================================================================

=======================================================================================

==============================================================================================================

========================================================================================================================

PHH - 4th. September 2012.


Delete via changes

We have seen in the last subsection how we can easily save any changes we make to our items in the

query collection.

Now we need as easy a way to remove any unwanted items from the collection.

I have ready Julia's text and find that she seems to be making hard work of things, possibly because she

is NOT at GUI guy, and maybe has limited experience of WPF as well.

Anyway, I thought her suggestions for both Deleting and Inserting were unnecessarily complex and fiddly,

as well as seeming to me to negate the whole point of EF4 - which is not to try and code things ourselves !!

So, with these things in mind, I will propose my own standard guy's way of doing 'Delete'.

My Rationale behind 'Delete' :

We have query items in a collection, if we change the collection of parts of any item in the collection, then we

can use a line line piece of code to saves these changes.

Changing the collection is either adding or removing items from it. Changing the properties of items is editing the

individual fields on a form.

Any GUI guy knows that there are certain GUI controls which facilitate adding and removing 'rows' or 'records'.

On our first (Main) window we have such a control, it is a DataGrid control.

If we are to use the DataGrid control on our 'MainWindow' form for trials and tests, then we need to add a 'Save'

button to the form, and the supporting code behind it.

However, before we look at details, let us see from some images if the approach works for us.

Checkout the following image in which I have highlighted the row with 'CustomerID' equal to 13, and then

simply pressed the 'Del / Delete' key on my keyboard.

I then clicked the 'Save Changes' button to produce what you are looking at - see below :-

================================================================================

Well, the record / row with 'CustomerID' of 13 has gone from our DataGrid (happened immediately) but has

the data in the SQL Table been affected at all ?

In the following image we see that the row/record seems to have gone - Oh! and that is also true if I Order By 'CutomerID',

which is what we should have done in the image - as the SQL Server returns data in an unpredictable order, unless

specified.

==================================================================================================================

Here is the correct version, including the sort by clause :-

==================================================================================================================

So if this appears to work, lets now set ourselves a task of removing a chosen row, look two images above, to see line

16 for 'CustomerID' 18, this has all 'test' entries. Lets remove this - see below :-

=================================================================================

Above I have highlighted the chosen row, and am about to press the keyboard delete key.

Now in the following image I have just clicked the 'Save Changes' button, after the row 'disappeared' :-

=================================================================================

So now the big test, what is the SQL Table like after this process - well answers seen below :-

=======================================================================================================

Even with the sort by 'CustomerID' the record can't be located - it has been deleted.

Now let us move on to see what our code is like that makes this happen.

Although the required 'extra' code is not much, we do need to make some changes to the existing code, so

that scoping is correct for our new and existing lines.

I have followed the code we got to work for our second window class, so it will be familiar to you.

First I added a few namespaces to allow our code to be shorter and clearer, as well as a few class variables :-

================================================================

So the scope of the defined variables in lines 25 - 27 will be 'class wide', anywhere in the class.

In the following image I have simplified the code lines, as well as commenting and deprecating the 'customersQuery' method.

With simplified code we can do all we have to in one single method, and that is the event handler for 'Window Loaded'.

So effectively lines 87 - 90 are existing lines, and lines 93 - 104 are extras, for the saving process - check this out below :-

=================================================================================================================================

The above image shows we have not done much new, and also nothing too complex, complicated, or plain 'clever' !

Now lets see the small changes made in the XAML designer and editor - see below :-

==================================================================================================================================

Once again, nothing much, and also similar to what we have done previously.

Going Further :

Okay then guys, we can easily achieve a DELETE using the DataGrid control, but we now need to examine which other controls allow

us direct access to the underlying collection.

If we can get access to the underlying collection from other controls - like ListBox, ComboBox or ListView - then we can use these if

we so choose to do so, to remove selected items.

PHH - 4th. September 2012.


Insert via changes

Okay guys, we are on a 'roller' after the Delete section ;-)

If we can use a DataGrid control on a WPF form to highlight and delete (remove) an item from the query

collection, and have the collection changes persisted to the back-end server, we should be able to add

another item to the collection by entering an extra row at the bottom of the DataGrid.

I say the above simply because I remember of old, using DataGrids and adding extra details at the foot of

the data presented in the control.

In the next images we follow through such an entry (new item) and note that the Primary Key identity may

be an issue - simply because it accepts a value - BUT - we know the SQL Server is taking care of issuing

new PK values.

Lets give this a go - checkout the details I have entered into the cells of the 'DataGrid' on the last row :-

=========================================================================================================

Okay then, so we wish to add our friend Donald. In some ways you could say we are not 'ducking' the issue ;-)

Lets see if we get any error boxes when we try to do a 'Save Changes'.

Study the following details carefully :-

==========================================================================================================

Oh! that is interesting, the detail in the above image just after we do a save, shows that the value in the grid cell

has changed from 9999 to the new value of '25'.

So we see some sort of feedback immediately, and directly on screen.

Here is the view of the data from Management Studio - check this out below :-

======================================================================================================

Okay then, we need to experiment more I feel .........

Further Testing - Inserting :

Let us do another test in which we supply a few fields but NOT the identity.

Oh! it is not possible to leave the identity 'blank' as when we click into another cell in the last (blank) row a

value of zero is automatically inserted into that cell, whether we like it or not - that must be to overcome the 'NULL' situation.

However, if we study the next image we see that we can't leave the other 'blank' or possibly they are set to NULL.

====================================================================================================

As you can see above, the error message box is from our Try/Catch, and say that we can't have NULL in the 'City'

column. The City column of out 'DataGrid' is the first blank one shown in the above image.

However, since the error message refers to the SQL Table, then we ought to check what settings we have on the

Table itself.

Checkout the following details from Management Studio :-

==================================================

Yes, we look as if we need to set default values for these other fields within our EDM, as we are able to provide

default values - we could just make them empty strings in this case.

Look to the child subsection from here - the one entitled 'Setting default values in the EDM'.

Now we need to explore other controls for 'inserting' capabilities.

Trying Other Controls :

PHH - 4th. September 2012.


Setting default values in the EDM

Previously, we came across a situation in which we wished to add a new collection item but did not

wish to set all the fields that existed for that item.

Because the SQL Server Table specifications on each column were set to 'Not NULL' we got an error when

we tried to 'Save Changes' - simply because we had our defaults in the Entity not set at all.

Well, we are to put things to rights in this short subsection - let us use the Customer Entity for the

purposes of learning.

Remind yourself of the Entity and its related detail in the SE pane :-

=================================================================================================

And now, if we focus on the 'City' property of the 'Customer' Entity we see a 'Default Value' attribute.

Remember we can use the term attribute and property interchangeably, so as the text is easy to read etc..

Studdy the next image where I have entered a pair of double quotes - in error as it would seem to turn out !

=================================================================================================

No !!! The good idea of typing an empty string as "" is not liked for some reason, and nothing is saved !?

We need to find something else it would seem. Lets experiment with the properties input box / field and

see what we can do - see the two images which follow, and how we can only select (None) unless we try

to enter some text for ourselves - check these out, to see the drop list options, and what we can do ourselves :-

===============================================================================================

And the next image shows nothing else (or extra) in the drop list :-

================================================================================================

In the next image we see an empty (blank) input box - you will need to try this out for yourselves :-

===============================================================================================

Don't select '(None)' that means 'NULL' I am pretty sure.

But instead make sure that the input box has no characters at all, if you like add some visible characters

and then delete them to satisfy yourself that none are left.

Yes, I think we have a viable way of setting a default string ;-)

A test shown below for Mary Malone, seems to work just fine for me :-

=======================================

And then saving this row we get the following :-

================================================================================================================================

First thing to note is that the 'CustomerID' field has been allotted the next value by the auto-increment of the PK feature.

Note also that for the above test we had all five fields, Address through Country, set as a blank in the properties box.

Not '(None)', but zero characters, it just looks empty - a bit tricky I know, but it works OK.

Basically we are removing the default of a NULL, which is what '(None)' seems to be.

I hope this stuff comes in handy later with our EF4 work, it certainly looks promising.

Time to move on, see you in the next subsection ...........

PHH - 4th. September 2012.


Read / Only - DataGrid

Okay then you 'VERY safety conscious guys ! ;-)

I here some of you say that you do not want your customers and clients to be able to either add new rows or

even delete them.

Well, do not panic, help is at hand in the shape of two useful attributes on the 'DataGrid' control itself.

======================================================================================================================================

It would appear that the default values for both of these attributes (shown above) is 'True', so that if they are

not shown in the XAML script they are taken as default values.

With these specifically set as 'False' we see a different set of behaviours with our 'DataGrid' control.

First of all, lets see if we still get an empty extra row at the bottom of the grid contents :-

==================================================================================

Well, no matter how hard I try I can' force one to appear, when before it was so easy to do so.

The conclusion is therefore quite simple, without this extra line we can't Insert / Add new items to

the underlying query collection.

So what about deletion, or removal ?

Checkout the following image :-

=========================================================================================

I have highlighted the line I was wishing to remove - Bill Brown was to have GONE !

But, unfortunately, the Delete Key (Del) on the keyboard is now unresponsive, and there is no right

click context menu either.

So is all our data in our grid safe ?

Well, no it is not - we can still edit the cells and rows that exist, just not delete them or add to them.

Here is Mary being edited - see below :-

====================================================================================================

And when we click the 'Save Changes' button we get no error message boxes either.

====================================================================================================

However, the data has been placed in the back-end database by the SQL Server - see the following image :-

=============================================================================================

Now this is simply because the ability (or facility) to be edited, is determined by another attribute of

the 'DataGrid' control - check this out :-

========================================================================================================================

In the above image script line 20 shows the 'IsReadOnly' attribute (the default is false).

When set to 'True' we can't get access to the cell contents for editing, but selection will still be an option.

========================================================================

No matter how hard I try in the above situation, the cell will not display the input box in edit mode.

Combinations of Safety Levels :

I will leave it to you to work out what you can and can' have between the three settings we discovered above.

It would seem that if you have either Delete or Add enabled, and working, you must then also have R/O set to 'False'.

You can't have it both ways - cake and eat it etc.. ;-)

Time to move one, see you in the next subsection ......................

PHH - 4th. September 2012.


working script and code

PHH - 5th. September 2012.


Towards the MVVM approach

PHH - 1st. September 2012.


Chapter 11 - object 'Code' first

As we start on our journey into exploring 'Code First', let us begin with a few choice statements from Julia Lerman

et al, and remember to refer to her / their text books (or eBooks) on this subject, and also DbContext - see the

introductory section on books.

'Code First', 'Database First', and 'Model First' are all just ways of building an Entity Data Model

(EDM) that can be used with Entity Framework to perform data access.

Once the model has been built, the Entity Framework runtime behaves the same, regardless of

how you created the model.

..............................................................

Microsoft refers to the 'Database First', 'Model First', and 'Code First' options as "workflows"

(e.g., the 'Code First' workflow).

That’s because each of those options is really a set of steps, whether you execute the steps

yourself, or the steps happen automatically.

.............................................................

'DbContext' is a lighter-weight version of the Entity Framework’s 'ObjectContext'.

It is a wrapper over 'ObjectContext', and it exposes only those features that Microsoft found were

most commonly used by developers working with Entity Framework.

......................

DbContext also takes care of a lot of common tasks for you, so that you write less code to achieve

the same tasks; this is particularly true when working with 'Code First'.

.................................................................

Just as DbContext is a simpler wrapper around the ObjectContext, DbSet is a wrapper around Entity

Framework 4’s ObjectSet, which simplifies coding tasks for which we normally use the ObjectSet.

..................................................................

The combination of the 'model XML', the 'database schema XML', and the 'mapping XML' are

referred to as metadata.

.................................................................

Because there is no XML file with 'Code First', it creates the in-memory metadata from

what it can discover in your domain classes. This is where "convention and configuration"

come into play.

Okay then guys, we seem to have been promised an easier time with DbContext, and DbSet, so if we struggled a little while

working with ObjectContect and ObjectSet, things will improve as we go along.

After some reading ahead of the text book, and some other small bits of research, it would seem the 'Object First' is the

technology we guys should embrace - unless we have reasons to choose otherwise.

Later in this chapter I will attempt to use 'OF' / 'CF' to create a nice new colourful DB for the Olympics 2012 - there is loads

of very useful and accessible data on the web ;-)

First lets try and make Julia's first small example from her chapter one work in our new Win8 / VS11 software environment.

Time to get going ................

PHH - 5th. September 2012.


Making a Good Start

Okay guys, I have just spent some time this afternoon getting to grips with the 'live' stuff of making 'Code First'

actually work on my Win8 and VS11 system. No good just reading and learning, at some point we have to 'do'

and make things happen ;-)

There have been some joyous moments and some frustrations, whilst doing this.

However, I have to say that I fear the issues and problems were due to the incomplete details in the text of

Chapter 1 of 'Code First', as good as the rest of it is ;-) Still, nobody is perfect, so I won't criticise any more!

Even with these stumbling blocks, I feel it has been a worthwhile journey, as I have learned a lot more by finding,

and then correcting, the small but 'show stopping' omissions etc.. Below I share some of these with you so

that you see and learn a few more things as well.

So on a positive note, read this from Julia et al first :-

Core to 'Code First' is the concept of conventions—default rules that 'Code First' will use to build

a model based on your classes.

For example, Entity Framework requires that any class that it will manage. has a key property.

'Code First' has a convention that - if it finds a property named 'Id', or a property with the combined

name of the type name and 'Id' (e.g., 'PatientId' ) - then that property will be automatically configured

as the key.

With that in mind I can start my detailed report on what I did, and how I eventually got good success too ;-0))

Doing the following simple first test / demo app gave me the ideas for the 'Olympics 2012' database project.

Lets start at a point after I have started a new WPF project, and the entered all the code exactly as the text

book suggested - here is my first restult, shown below :-

=================================================================================================================

Oh! dear, what does that mean ?

After some fiddling around I realise that the much acclaimed statement in the text book, about not needing to

provide a connection string for our server, did not wok for me with my MSSS 2012 ( 'Denali' ) install.

Luckily, because of the work done previously in these eNotes, I looked to the App.Config file, and took some guidance

for the information in Chapter 6 of JL's text.

Below is the string which works for me - AND - I notice that this is one thing which has improved by its simplification

over the previous ones needed !

Check this out below :-

==================================================================================================

For any guys coming from SQL work they will feel more familiar with this.

Now then, we also need to know which assemblies and namespaces we require extra to those supplied

by the in-built WPF template.

Since the JL text suggested that the code be simply typed into a C# project, we do need some extra supporting

references and pointers for the VS 'shell' to use.

Here is my full list, which supports a now working application - there may be more than just the essential ones :-

=====================================================

Now in the next image we see those I added, and I think I may be right in saying it was the first

of these that made all the different to the code compiling, so be aware ;-)

======================================================================================================================================================================

In the above image I am not aware of what the version number means - does 4.1.0.0 mean we are not using EF4.3 ?

We will see in good time, anyway the example does work by the time we get to the end of this subsection, so

lets keep going.

In the following image note the added line 15 for the extra namespace - check it out :-

===================================================================================

And although the added text lines are shown in your copy of the eBook/Book from JL, here is what I have

in my working copy of the example - first the Table type classes :-

==================================================================================================================================================================================================

Now we need to look at the 'VetContext' class with its still incomplete code around lines 74 :-

============================================================================

When I compiled and ran the code it did get part way through before it threw and error.

And by looking in Management Studio (MS) I could see that the database seemed to have been created

as I would have hoped - successfully that is.

Check out the detail shown in the next couple of images :-

============================================================================================

And now the Tables themselves :-

======================================================

Here are the Table details - showing column specifications :-

==============================================================================================================================================================================

You will notice that the EF 'Code First' system seems to have added another - one to do with MetaData :-

=====================================================

If we look inside we don't see a great deal to help explain what this is and for - but check this out anyhow :-

================================================================================

Okay then guys, what about this error message ?

Why do we not get any Patient and Visit data stored ?

The following image shows the connection string which MUST have worked as the error message is about Table

detail, and to get that far we must also have some Tables I would think !

Study the error message and see if it means more to you than it does me ;-)

==================================================================================================================

Well, after a bit of head scratching, and looking at the Tables etc., etc. I realised that we had a line missing

from our code creating the Patient record.

Note in the following image we have a table column / object property called 'FirstVisit' :-

===========================================================

If we now look at the inner message we get a bit more of a clue as it talks of 'datetime2' as the

data type.

Check this out :-

======================================================================================

If me now look back to the code we have used so far, we see no mention of this property, as

you can see in the following image :-

===============================================================================

So, going with the flow I added the line now showing below at line position 76 - check

out the following :-

======================================================================

Now when we try to compile and run, we get no error messages, and when we look in MS at

the Table contents we see this :-

=====================================================================================

So if the Patient table is correct, what of the others ? Here is the Table for 'Visits' :-

================================================================================

And then finally, that for 'AnimalTypes' - see next image :-

=================================================================================

So, it would look as though we can now get all three Tables to be 'INSERTED' to (updated in general parlance).

New records have been inserted, but we often talk of the table data being updated, meaning all recent or current

data items as made to persist in the database.

Summary :

Julia's text works fine if we correct and include a couple of small things which are 100% 'Show Stoppers' otherwise.

I have to say that the general approach seems VERY simple, clear, and straightforward.

What I am interested in knowing however, is what happens to the data if I change (or add) a property in a class then

re-run the application. I think I feel an experiment coming on ;-)

Making a few Changes :

Okay then, a big topic, and a little experiment to get us going - just so we get a flavour of all this stuff.

First we will make a couple of changes to the property structure of our classes 'Patient' and 'Visit'. We will then add some

data to the method making new entries, and run the app to see what happens.

Check this out below :-

============================================================================================================================================

Okay then, so what has happened ?

Well, it would appear that the EF / 'Code First' system has picked up on the fact that our internal code 'mode' is

not 100% in correspondence with the existing SQL database.

However, it also looks as though we can make some code updates so that our application can recreate the newer

form of the DB, as long as we handle the data aspect for ourselves.

For the moment, with this first trial, lets look at some positive results where we have changed our code accordingly.

The following details show the new 'Comment' column / field in our Table :-

=========================================================================================================================================

Let us see what we have done to make this happen - check out the following code, the green side bar icons

indicate where code changes were made :-

===============================================================================================================

Yes, line 94 is the one which allows the code to continue, and to drop the older versions of the Tables, as well

as recreating new versions.

It would appear from the name as if the whole database is dropped, and then fully recreated, and the operation not

done on a Table by Table basis. So all data will be lost, in all Tables.

In reading some MSDN and JL book information, it would seem that we have an option to have some sample and test

data which can also be loaded into the new Tables at the same time - we need to look into this as it would be quite

helpful while developing an application. MSDN calls this "seed the DB with data".

It also informs us that the default behaviour is to "Create DB if non exists".

We need to look into this aspect in more detail at a later stage, for now we can just put the idea to one side.

Time to move on ........................

PHH - 5th. September 2012.


Mapping - way to define Entities

PHH - 20th. September 2012.


Seeding with Data

======================================================================================================

==================================================================================

=====================================================================================================

========================================================================================================================================================================

============================================================================================================

=============================================================

===================================================================================================================================

======================================================================================================

PHH - 6th. September 2012.


Damaging the Database

Okay then folks, we now need to try out an important experiment as far as Code First is concerned.

I have been wondering just what is required before the 'IfModelChanges' condition is concerned.

Yes, we have seen that if we change our classes at all, even one property on one class, this condition

seems to fire. BUT, what if we 'damage' or change the actual DB from the MS environment ? Then what ?

============================================================================================================

===========================================================

=================================================================================================

=======================================================================================================================

==============================================================================================================

=================================================================

=====================================================================

================================================================================================

=========================================================================================================================

====================================================================================================================

=================================================================================================================

=================================================

PHH - 6th. September 2012.


Going Further - Olympics 2012

Well guys, after weeks of fighting to get into EF4 and all related stuff like LINQ and Lambda expressions, it is time

to try out some nice and colourful stuff with a completely new database for the VERY recent Olympics 2012 in London.

I am doing the Olympics (able bodied) as the Para-Olympics is till taking place. And how good is that ? I am really

enjoying all the various sports and the spirit of the Para Olympian competitors.

One good reason to make a database for the Olympics is that there is so much correct data available on the web.

Yep! both full details (thoroughly checked) and also some icon images which can both improve, as well as widen the

scope of our DB activities. For example I plane to keep images as binaries in the SQL database. This is a first

for me as previously the versions of MSSS were not up to a lot when it came to BLOBs (Binary Large Objects).

Anyway, here is the link I have found and used, and VERY good it is too ;-0)

http://www.london2012.com/schedule-and-results/full-schedule.html

===============================================================================================================

Okay then guys, lets talk of how things will change as we move through this exciting Olympics section.

How this Section will Develop :

Because I am learning about Code First (CF) as I am creating and developing this database example, based on the

London 2012 Oplympic Games, we need to appreciate that some details you see displayed may get updated, and

changed as we go along with improvements, and getting features to work at a GUI level.

I will do my very best to not leave in anything misleading, but you will still see some changes in the images displayed,

and the final working code and script.

A good example of this is that I am currently changing the whole content of the subsection to follow called 'Basic Classes'.

Yesterday I placed in that section a good set of 'starter' classes, but today these have come along a lot, and the new

developments ought to be shown to you.

PHH - 5th. September 2012.


The Available Details

http://www.london2012.com/schedule-and-results/full-schedule.html

===========================================================================================================

PHH - 5th. September 2012.


Nations

==============================================================================================================

===============================================================================================================

===============================================================================================================

===============================================================================================================

==============================================================================================================


Sports

===========================================================================================================

==========================================================================================


Venues

===========================================================================================================================================================================================================

=========================================


Events

=================================================================================================

==============================================================================================================

=============================================================================================================


Athletes

===============================================================================================================

================================================================================================================

=================================================================================================================

===============================================================================================================


Results

Enter topic text here.


Medals

==============================================================================================================

===============================================================================================================


Records

Enter topic text here.


Connection String

I won't make a fuss about this, whatever the text book says (Code First) about not needing anything at all,

and you just press F5 for run with debug.

I found I needed to place this string into App.Config in the SE pane.

Yes, I know, the string fits my system - BUT - this can be easily changed to suit yours.

Check this out below :-

======================================================================================================

All you need to change (for your particular PC platform) in the above script is the 'connectionString' itself.

This you will find in the drop list provided by Management Studio - see the following image :-

As far as I can see (and tell) the rest should work for you.

Good Luck ...............

PHH - 6th. September 2012.

Addendum :

A big spin-off is that once we have developed and tested our app we can set the 'connectionString' attribute in the 'App.Config'

file to another value - AND - if we make this the LocalDB option then we can easily move our newly developed app over to a

customer's (or clients's) site, or PC platform.

Checkout fully the image shown below :-

====================================================================================================================================================

As you can see in the above image the 'connectionString' is now :-

"Server=(localdb)\v11.0;  Database=Olympics2012;  Trusted_Connection=true"

where only the first of the three sub-sections has been changed.

We also notice that the '(localdb)\v11.0' is independent of which PC (or machine) installation is being used.

So a developer can quickly install the 'Local' version of SQL Server 2012 ('Denali') as the copy over, and run the

new app - as long as the App.Config contains the above text.

An alternative commenting style is shown below :-

==================================================================================

After a thorough 'live' test we see the following appear in the Object Explorer pane :-

============================================================

Notice the very first node title which contains the 'localdb' server instance name.

Obviously we need to make a couple of small changes to the initial code within our main application.

Checkout the following to see what is required - one possibility. that is :-

=========================================================================================================================================

I think this capability offers lots to developers moving to off-site situations, as just before a move

the connection string can be changed and tested to see it works with the developer 'localdb' as

this will be exactly the same as the one on their customer's PC platform.

Just Brilliant !!!

Time to move on ...............

PHH.


Attributes - Table, Column

[ .. if you are in a hurry, then miss this out and go to the child section called 'Fluent API' .. ]

It has been a little trick getting my References and Namespaces selected and specified correctly.

After my first attempts which would not compile, and improved to compilation but no results in the database.

Just there now I have improved (after reading a couple of lines in 'Code First' by Julia et al) to getting some

of the attribute syntax to work for us and the classes I have created.

In the following image we can see that the names of the individual Tables have no trailing 's', which is what

I wanted in the first place.

Check this out for details :-

============================================

Now the new code and attribute syntax which produces this is shown below :-

=================================================================

And when we look at the results of this code we see below that null/not null is correct, as is the

name of the column as 'SportID' and not 'SportId' - check this out :-

==================================================

I am still having a bit of a struggle with some of the other attribute syntax, but at least we are now getting

some positive results.

In order to get the above to function I used namespaces like so below :-

===========================================================================

Also I had to include a couple of extra References I seem to recall, so this is what I have now :-

================================================================

And we can even get the 'Schema' to be defined too - see below :-

=================================================================

Notice that in the image shown below we have the 'TestSchema' showing

for only the Sport table, as this is the only one for which we specified the attribute.

Check this out :-

==================================================

So I will now leave you to work out what I must have done to get the following newly created database ;-)

Note that the only table out of our control, and made by the EF4 / CF system itself, is still of schema

name '.dbo'.

=============================================

Still to sort out is 'MaxLength' - strangely enough !?

Anyway, we are 'on our way'!

*** Sorry ! *** change that last statement to '... on our way to using 'Fluent API' as in the child subsection which follows !

See you there, it solves all issues it would appear - now I use it all the time and like it a lot ;-)

PHH - 7th. September 2012.


using Fluent API - another approach

Having had such a problem with Data Annotations (DA) and their correct Namespace and assembly references,

as well as web articles which just seem to muddy the water even further - even from JL - I have taken up this

alternative approach which seems quickly to have given me better results than previously, when using the DA

approach.

Maybe things on the DA side of things will improve when public releases of the relevant software and frameworks

are made available to us.

Possibly, till then, I will follow through this 'Fluent API' way of doing things.

==================================================================================================

Okay then, lets make a simple start to all this.

Do however bear in mind however, that we will be moving towards grouping these together for each class, and then

adding them as a set of groups, one after the other.

For now, to make a start and see how they work for us, lets just add a bunch for the Sport class we coded earlier.

[ .. Note that the old DA text has been removed from this class .. ]

Check out the details below - very carefully :-

[ .. System.Data.Entry is required in the References section .. ]

................................................

................................................

................................................

=====================================================================================================================

What we see above is a method added to the end of the class we made called 'OlympicsContext'.

The new method is consulted just at the point that the Context object is to be created.

In the above code we have just bunched together a group of single lines, but we will see how to group these

in an organised fashion in a short while - just below in fact !

Tidying our Code with an Eye to Larger Apps. :

When the folks, I have read Julia et all in 'Code First' and have applied this to our Olympic Games 2012 database and

WPF application.

We only had to modify the above code somewhat, so as to make separate classes for each group of configurations, one

for each of our data classes - in the following example I have so far adjusted two, 'Sport' and 'Venue'.

Checkout the following details carefully :-

====================================================================================================

And of course we need to see that the earlier DA code have been removed - so check this out also :-

================================================================

Lets give Julia the last few words ...........

"For those who prefer to leave their domain classes alone, you learned how to use the alternative

'Fluent API' to perform configuration in the 'DbContext' class."

Oh! we had better do a re-build, compile and run, just to see we have not broken anything ;-)

=========================================================================================================================

Well, we can certainly see that our 'MaxLength' has worked for the first time - remember DA was giving us grief over this !!

Also the [Requried] was not compiling, whereas now we have it working as the extension method 'IsRequired'.

Personally, I see great possibilities in this approach, I intend to give it a 'real good go' ;-)

Time to move on, see you in the next section .......................

PHH - 8th. September 2012.


using DbModelBuilder class

============================================================================================================

=================================================================================================================================================

==================================================================================================================================================

=====================================================================================================================================================================

=====================================================================================================================================

===================================================================================================

================================================================================================

=======================================================================================================================================================================================

PHH - 10th. September 2012.


Basic Classes

Okay guys, try 'TWO' - this is now the second attempt at showing you some basic classes upon which

I have based the new 'Olympics 2012' demonstration CF database.

The following 'collapsed view' of the classes code is not in any particular order. Which is what you would expect.

Check these out below :-

==========================================================================

One nice thing about the VS11 facilities when coupled with EF4 is that we can use the 'Database First' approach to show and

display the Table relationship of our now existing SQL database.

Since we have already designed, updated, and built our 'Olympics' DB a few time (quite a few by now) we can use the latest version

we have to show this nice diagram below - check it out thoroughly.

======================================================================================================================================

This diagram goes along with the database and tables 'set' shown in the Management Studio (MS) Object Explorer (OE) pane

which we can see in the next image - see below :-

=================================================

If we now look at a few individual table structures we see that the 'Athlete' table is as follows :-

==================================================================================================================================

====================================================================

====================================================================

======================================================================

=======================================================================

========================================================================================

PHH - 8th. September 2012.


Improved Basic classes + F-API

==========================================================================================================================================================

=====================================================================================================================================================

=================================================================================================================================================================

============================================================================================================================================================

=====================================================================================================================================================

===========================================================================================================================================================

==================================================================================================================================================================

PHH - 10th. September 2012.


Classes with 'Dependency' built-in

PHH - 8th. September 2012.


Forcing a DB Drop & Create

Okay you guys, I think I have eventually 'cracked' this one ;-)

It took a lot of time and messing about, as there are few articles on the web, AND, those few that are there

have the wrong syntax for my latest versions of the software I am using !

A few sites have it marked in RED that "these now longer work !".

However, since the MSDN docs are also VERY 'thin on the ground', it was a bit of a struggle, especially since

I am also relatively new to C#, coming from Vulcan.NET.

So overall, I am VERY pleased that I have something which works.

Here in the first image is line 32 which gave me the first success !

Check out all the following details :-

=====================================================================================================================================

At the moment, the STATIC method being run from line 33 is within the Olympics 'context' class, this may well

change in the future, but it is sufficient (and okay) for now.

At the moment there is a 'tiny' amount of data being added before the 'SaveChanges' method is called on line 67.

This is simply to make things work nicely for me - BECAUSE - even if we have the option set for ''Always' drop and create,

this only happens (is triggered) if and only if there are changes made to our items collections in memory.

Check out the 'CreateAddSeeOlympics' method shown below - even though we are not 'seeding' in the standard way :-

[ .. we are using the term 'seed' to mean giving the DB some initial data .. ]

===============================================================================

Now that we know we have optional settings for what happens to the database - how it is created or over-written,

we need to see what all of these are.

Let us start with quite a handy one, that which only drops and creates if we have changed the code which affects our

in-memory 'Model'.

======================================================================================================================================

The third option is also the default option setting for CF and EF4 - to create only if none exists - check out below :-

======================================================================================================================================

So first of all with our settings and tests, lets see if the 'over-write' option works - BUT - we will only be able

to tell if we remove a table as a test - then when the DB is re-built, we should see the Table re-appear.

Lets do some testing ..................

Testing a Forced Re-Build of the Database :

Here is a useful test to see if the option for 'Drop and Create' is working okay.

In Management Studio highlight the 'Venues' table and from the context menu select 'Delete'.

Below is what I see in MS :-

===========================================================

This then produces the screen display like that in the first of the two images below - the LHS image.

After compiling and running the app with the Line 34 option to Always Drop and Create, we see the second

image in MS (RHS image) after doing a 'Refresh' on the Tables node :-

==================================================================================================

Refreshing option looks as follows - BUT - I have already done this and so 'Venues' is showing :-

=========================================================

*** NOTICE ***

What I have noticed however, is that the Table has been called 'Venues' which is NOT what I expected, since

the following image shows my code and the 'attributes' set :-

==========================================================================

As well as the table attribute being ignored I also see the column one is also ?!

Check this out below :-

=====================================================

I have noticed that reading the eBooks from JL et al, they have a different syntax for attributes, and it took me a while

to get my code to compile. This is something we need to sort out soon.

*** Continuing with our tests ***

CARE - be 'aware' !!!

The following image shows just how easy it is to do something which causes grief ! See if you can spot the error :-

=================================================================================

Yes, I copied and pasted (well dragged a copy actually) from the line 54 and forgot to change it in two places :(

EF4 and CF does not like this at all, as we can't have two similarly named entities or 'Sets'.

Here is what id should be like :-

=================================================================================

And also we need to see the new class for 'Continent' as well - check this out :-

=================================================================================

And with the 'If Model Changes' option being active in our code I tried to run the app once again.

Here is the code I used for the database setting - see below :-

=======================================================================================================================================

And then 'BINGO' we got what we were after, the DB was remade and after a refresh in the MS environment (shell)

I got this showing up in my Object Explorer pane - see below :-

===========================================

Okay then folks, we seem to be winning on this one, updating our DB structure to be in-line with our code model.

Time to move on .............

PHH - 7th. September 2012.


What are changes to the DB?

PHH - 8th. September 2012.


Adding some real data

The term 'Seeding' is often used to cover the action of getting data items into the newly created database.

There also seems to be a method associated specially with this, but we can also quite happily use the 'SaveChanges'

method as well. I have seen and read a few examples of both - we can find out the differences, if any/many, later on.

Let us start at the point where the application starts to 'run'.

Below is shown line 40 which runs a STATIC method called 'OlympicContent.CreateAndSeedOlympics' :-

=========================================================================================================================================

Note that we are using the database option of 'Always' recreate the DB.

So what does this STATIC method have within its code ? Lets start to look at what I have so far created and tested.

Checkout this collapsed view - all details :-

=================================================================================================

In the above image we see that we have a method to get a 'Photo', and in fact it gets any image from a file,

and puts it into a binary format suitable for storage in the SQL database.

As well as what looks like sub-methods, for adding smaller data 'sub-sets' we also have the main STATIC

method to 'create and seed'.

When we take a look at the next image we will see that there are signs of earlier code trials for initial testing.

Notice that the first two sections, for Gender and Medal type, could be now tidied up by encapsulation, into

methods called 'SeedGender' and 'SeedMedalType'.

Checkout the rest of the following details :-

================================================================================

================================================================================================================================================================

================================================================================================================================================================

=================================================================================================================================================================================

================================================================================================================================================================

====================================================================================================================================================================

PHH - 8th. September 2012.


switching to Enums

============================================================================

PHH - 9th. September 2012.


Adding Event details

Okay then guys, we have come a way with improving the way we add. or seed, our data, just after we re-create

our SQL database for the Olympic Games.

Before we get to look at what I have done to input some Swimming data fro the Event table, we need to ses the

shape of the tided code.

Check this out :-

====================================================================================================

=============================================================

Within our DbContext based class we have now greatly tidied the method entitled 'CreateAddSeedOlympics', as we see two

images above.

This now just refers to other methods which accept one parameter the 'context' object being built up, or added to. Note we still

have only one call to 'SaveChanges'.

Line 99 of the code now causes the new 'Swimming' method to be run, and this is fully shown below :-

[ .. a few entries into this data creating method have been collapsed for ease of display .. ]

===========================================================================================================================================

If we now re-build and run this code we get a new DB with the following data entries :-

=======================================================================================================================================

At the moment one downside is that we have not as yet specified that we need the 'SportID' column to be a foreign key (FK)

and relate to the PK of the 'Sport' table.

Data Annotation / Fluent API 'stuff' :

At the time of running the app and getting Event data uploaded, we have the DA details in the attributes as

shown below :-

=================================================================

We need to make a suitable 'Configuration' class for/called 'EventConfiguration' which is similar to the first two we made

in a previous subsection.

Lets try and make a new one now ...............

=======================================================================================

And for the purpose of testing and checking, I have just commented the attributes as seen below :-

===========================================================

So we now need to compile and run - hold onto your hats :-

=======================================================

Well, as you can see above, the Table and Property details have been made by the 'Fluent API' approach,

much as they were from the 'Attributes' code. SO now I can delete the commented lines.

And this is what we now have :-

===========================================================

So how do we now force a relationship between the 'SportId' column and that of the PK field in the 'Sports' table ?

It looks like a task for searching through the 'Code First' text from JL et al. Fingers crossed !?

Success - Look at this :

Okay you guys, a bit of a fiddle through a somewhat slightly confused and disorganised Code First text, but its there

if you dig deep enough.

Lets look at what I can make happen, now that I know how ;-) Checkout the image below :-

===========================================================

Being an experienced SQL guy I am now comfortable with what I see above - the FK symbol next to 'SortID'.

However, this does mean we will need to edit out seed data code to change 'SportId' to 'SportID', but that is trivial

once we know what is going on.

We need to examine closely the code which is now in the Event class, only a small change - BUT - a crucial one.

Check this out below :-

=================================================================

[ .. it would seem that to get the CF system to do its 'automatic thing' the column / field names must be identical .. ]

[ .. if it were not for fully exploring the EF/CF boundaries I would have just stuck with the default convention of 'Id' and ]

[ .. not tried to force the issue of doing things my old way !! - so be WARNED .. ]

And to go along with the above changes on lines 357 & 358 we need need to comment a line (or remove it)

in our related 'configuration' class - see below :-

===========================================================================================

In order to make it possible for the data to read in successfully I had to change the casing of 'Id' to 'ID' - checkout the following :-

===========================================================================================================================

Okay, then now we know how to get our Foreign properties / fields back to what we had in SQL and MS days, then

we can apply our new knowledge to changing other classes, like Athlete and Entry.

Look out for these changes and improvements (and trial an test data seeding too) in the following sections.

Before we leave to learn others stuff, I nearly forgot to point our a VERY import but apparently small issue of 'timing'.

I found that if I did not force a save of the changes I had made to the 'Sport' details while 'seeding', then I got an error

while trying to upload to the DB the Event record data.

Once I realised from the Inner Exception details on the MessageBox, I did the following to the create and seed method :-

======================================================================================================

By adding the line 99 to make sure all earlier data had been seeded, then code on line 102 ran smoothly.

It would seem to me that when there are many changes being tracked by the DbContext object, we can't assume that they

will be done in the same order as we code our lines.

I could be wrong on this, BUT, we do need to be aware, and after all, what's another 'SaveChanges' between friends !?

Time to move on, see you in the next section .............................

PHH - 9th. September 2012.


Adding Athlete details

Right then folks, before we can start to enter (or seed) data into our Athlete table we need to make a few

changes and improvements to the structure of the table, and add some extra columns, and the likes.

Let us start by examining closely what I have showing in my Management Studio (MS) 'shell'.

Check out these details, notice the Keys :-

=====================================================

So in the above image we have one Primary, and two Foreign, Keys.

We can also see above some field width restrictions, and some 'not null' requirements. And the Photo

field is just one field which is mandatory.

Let us now more further, and checkout the 'Fluent API' specification which produces the SQL Table at run time.

Each of these specifications should be seen in the previous MS 'Object Explorer' pane image.

==============================================================================================

Okay then, all that seems in order and quite sensible too. So what does our code look like which now

specifies the 'Athlete' class ?

Well, make a thorough study of the following image in which we see various subsections of the personal

data for an athlete.

Note the entries are not set as mandatory, as this then allows them to be entered at a later stage, when the athlete

details are already stored on the data source, back-end device. Checkout the following image :-

=================================================================

Well, the above looks clean and tidy, and even organised, if I say so myself ;-)

I also have to say that I quite like the DA attribute 'stuff' being in a separate class. This aids the clarity,

and I think it will be even more obvious when we need to make Dependency Object lasses for data binding.

Now then, how about viewing some success at data seeding, or inserting, for a couple of well known GB athletes.

Checkout the details shown below from my MS 'shell' :-

============================================================================================================================================

We have an Athletics guy and a Swimmer.

BUT - we need to be aware that until we load the complete set of both Sports and Nations then the values used here are likely

to change, and so these will then be incorrect.

Let us remember that we are probably much better advised to enter the Athletes through a GUI front end, one we have the basic

data items pre-loaded. So we can then check out any existing athletes and make changes is required.

For the moment the above is sufficient to allow us to do our tests and trials.

Now we need to see how we have integrated the STATIC method to seed the Athletes - see below :-

==================================================================================================

Once again we need to take care on what data has been loaded by the time we try to load new data - remember a

'Save' too many better than uploading errors of some sort or another.

And now for the working code which has been tested to load the two selected athletes. Study the details

most carefully, and try to understand what each is doing.

=================================================================================================================

Notice that the order of the properties in the constructor does not matter, since the properties are specified.

PHH - 9th. September 2012.


Adding Entry details

=========================================================================================================================================

Manual entry in the MS editor gives :-

[ .. when doing this manually I did specify 'On Update no Action .. ]

[ .. we need to find out how to do this from our code in some way or another .. ]

===============================================================

=====================================================================================================================================================================

===============================================================================================================================

==============================================================================================================================================================

And here are how the two tables look after the code has been compiled and run with the convention removed :-

===================================================================================================================

This looks as though it will do quite nicely for our Olympic Games DB purposes ;-0)

Now - Adding some Entry Data :

Although this operations is one I would prefer to be done at a GUI level, and one which I expect to do that way, quite

a number of times, we need to see if we can get the same type of code 'seed data' approach to work for us.

PHH - 9th. September 2012.


Getting some first GUI displays

Okay guys, up to this point we have done a LOT of work on the database and the Code First without

seeing any results on the surface of our GUI screen.

Before we get into coding and scripting details lets look at what can be easily achieved when we use

the results of our hard work with CF - see below :-

===========================================================================================

Okay, I know, its just some standard list displays - BUT - it was all done by code ;-)

Let us see what our main screen initialization code section looks like to display such details :-

Check this out thoroughly and carefully :-

=============================================================================================

===================================================================================================================================

================================================================

============================================================================================================================

======================================================================================

PHH - 10th. September 2012.


Getting back Athlete information

=====================================================================================================================

===================================================================================================================================

Formatting the Date for their Birth :

At first this can seem a little tricky - but it is easy when we know how :-

=========================================================================

The results look like that shown in the following image - see below :-

====================================================

An alternative is a fuller form as seen in the next two images :-

==============================================================================

And so we get just day and month details - long and short :-

===================================================

If you wish to see more examples of alternatives see the "Tip & Tricks", Appendix 'A'

Going Much Further :

I think it is at least a good idea here, to show you the final form of both the output displayed Data Template,

as well as the code and script required to show it.

Lets start with the final screen display - see below :-

==========================================================

The details on the template shown above come from three separate SQL tables.

First of all have a look at the LINQ expression query which gathers the information together on each athlete :-

===============================================================================================================================

Notice in the above code we are using a newly created class, one I have called 'AthleteFull'.

Checkout the following image details of this new class - see below :-

=============================================================================

In the above image you will see that we are actually gathering three separate 'pictures' or images. The

national flag, the sport icon, and also the photograph of the athlete.

Here is the tidied XAML script of the 'DataTemplate' used for the final display of athlete details :-

[ .. note lines 55, 59 & 61 in particular .. ]

=========================================================================================================================================

The syntax for 'StringFormat' in the above script lines changes compared to that when within the Text attribute, and as

a parameter for the 'Binding' syntax extension.

It would seem to me that we just have to get familiar with the variations in both, and also do a fair bit of trial and error.

PHH - 12th. September 2012.


working code and script

PHH - 8th. September 2012.


Chapter 12 - developing 'Olympic Games'

In previous sections we have looked at the possibility of an Olympic Games 2012 application - we have

really being exploring the possibilities, or making a 'proof of concept' applet.

What we now need to do is move this forward from just the underlying database and Code First stuff, to a

fully working application - working in as much as it allows a user to enter some new data items, and save

these to the back-end data source.

Certainly, we need a different, and newly designed main screen. The earlier one we experimented with is

OK for playing and experimenting, but not suitable for a working app. We need the equivalent of a menu option,

or choice screen.

Since I feel that menus are a little dated in fashion terms, and tabs were over-used by many, I will go for a simple

screen where we have only two tabs and then Image controls for visual display of options.

Obviously to make such a front screen work nicely, we need some suitable images and icons ;-)

Before I show you any images of what I am trying to develop, let us realise that the two Tabs are to allow us

to see and use the two different 'sides' or 'modes' to our apps - "Viewing Information", and 'Changing and

Entering Data".

The following image shows what I am after, and where I may be going - it is only part complete at the moment.

Check it out :-

[ .. I may add some sort of label for each image button, because Buttons are what they are ! .. ]

======================================================================================

In fact if we can find a clear and suitable image of the Olympic Rings we can do something like this below,

and have the icon showing in the task bar as well as the Form icon at top left of Form :-

============================================================

Yep! I know, its not clear enough - we can do better !

This is not much better - but a try, never the less :-

==========================================================

The problem is having an image which holds its own when very small.

Anyway, moving forward we see the following 'menu' screen, complete with labels :-

=====================================================================================

We will give this a go to see if it works for us.

PHH - 15th. September 2012.


Adding more Forms - structured approach

Okay you guys, before we rush off and start to add more Forms to our Olympics application, in an

attempt to make it more interesting, and give it some fancy features, let us pause a while, and think

of structuring our application.

When I talk of 'structure' I mean that we see in the SE (Solution Explorer) pane. How our PRG files

and resources are kept together in folders - or since it is a tree we should talk of 'nodes'.

As you may be aware by now, WPF works best (at all?) if we leave the 'MainWindow' details well alone.

By this I mean that the first WPF form added to our new solution/project sees always to be called 'MainWindow'

and in the past I seem to have tried and failed, to rename and restructure this under a node.

So I will leave 'MainWindow' as it is and place any new ones under a new node (folder) named 'OurForms'.

Lets try the right click in our project entry of SE and bring up the context menu :-

=======================================================================================

When you are finished you should have this - as seen below :-

============================================

Now we need to right click our new node so that we can add a bunch of children, which are all WPF forms.

Lets do one first and then we can do a bunch. here is how I am starting :-

====================================================================================================================

And we see that we get an 'Add New ..... ' screen into which we can enter a suitable name for the Form.

Check out the following :-

=============================================================================================================

Then the results of our labours show in the SE pane as that below :-

=============================================

If we keep on going, adding more and more Forms, we get that which we see in the image below.

Note that the 'Addit' means 'Add and Edit' - so we ought to make any 'Addit' form allow new entries

as well as us changing existing details.

Check this out :-

==============================================

Since we now have a new (albeit currently blank) form for navigation called 'GamesOptions',

let us make this the opening Form for our application.

In the editor open the 'App.xaml' file and change it as seen below :-

================================================================================================================

Now try and compile and run the app, and you will see this shown in the next image :-

========================================================================================================================

Uggh ! what is going on ?

Well, don't forget our new 'structure' we have another 'folder' level and so we have gotten the name-path wrong.

Try changing the entry in the 'App.xaml' file to that shown below :-

===================================================================================================

Sorry ! - yet again you will get an error box similar to above, so what is wrong ?

Well look at the following image to see a correct 'Uri' :-

==========================================================================================================

Yes, the above script change does work, and we see our not very exciting new Form opened as the

first one in our app execution sequence.

It may also interest you to know that a forward slash in place of the backwards slash, also works when we run it.

Checkout the change below :-

=========================================================================================================

Now let us go to the XAML edit / designer surface, and make some suitable changes.

With the blank new Form on screen, drag from the Toolbox a Tab control and drop it in the middle of the Form.

Then edit the XAML script to be similar to that shown in the following image - remove Margins and Height and Width,

use this as your guide :-

===========================================================================================================

Now we need to make a few changes, just to get us on the move ;-)

In the following image check out the green markers at the LHS of the text editor, and make suitable changes

to your application - we will improve the title on the Form, as well as naming the Tabs, and also bringing a

little colour into all of our lives - check this out below :-

===========================================================================================================

Don't forget that we have also increased the dimensions of the Form as well.

Planning Ahead :

Now guys, if we are to be able to place a few buttons on the Form in some regular pattern, then we need a grid

marking out - this is easy so just follow what I have done, and this is seen below :-

==========================================================================================================

The part of the XAML script which creates the basic buttons (as seen above) is not very complex, and is shown

in all details below :-

===========================================================================================================================

If you are new to WPF then see how the row and column is defined above. Since all buttons are within one cell

of the grid, we don't need 'ColumnSpan' or 'RowSpan' attributes being defined.

One important thing to notice is that the 'Content of each of the Buttons ia between the Tags, as opposed to being

defined between double quotes like the other attributes.

I did this on purpose, as we can now place an image on the Button surface - but in scripting terms this is equivalent

to 'nesting' an image within the 'Button' tags. Lets give this a go to see how it looks.

Checkout how we 'nest' the image within the Button tags - I have grabbed a whole bunch of new images from the official

Olympic web site so you wee need to copy mine from my .NET solution or find your own suitable ones - check this out :-

============================================================================================================================================

As you see in the image above, we have made sure that the selected image for the Button 'coverage' is fully stretched.

We have also given it a 'Tooltip' so we can confirm that we have the right button when we hover during execution.

What we now need to do is try to add an event of the 'Click' variety to the Nation button to see if we can get it to

function correctly.

In the design surface, bring into focus the 'Button' - I suggest clicking in the Tag of the XAML script - and then move to

the Properties Pane. See below for before and after double clicking within the input box for the 'Click' event.

[ .. if you don't know it, the little lightning symbol at top 'RHS' of the Properties Pane is for 'Events' .. ]

===================================================================================================================

After the double click action we get two things occurring, one in script and the other in code - see below :-

=======================================================================================================================================

And here is the code we got :-

=================================================================================================

Fine so far, lets now see if we can get a simple event response by adding some code to the event handler.

Here is what I got when I spent a few seconds adding some code - lets view the results before we see the code.

Study these details carefully :-

===============================================================================================================================

Let us take time out .................

Which Control ? - which Event ? :

Whoooh ! - I here some shout, we added the event and handler to the Button control, but when we run our app we are clicking

on the Image itself. How is this ?

Well, first of all it works OK ;-) Secondly, WPF has event bubbling, which means that for nested controls, if a certain type of

event is not handled locally by the control itself, it bubbles up the chain to the next highest, in this case the Button control,

where we do handle it.

So with all our bubbling work apparently OK< lets move on to hooking up with our handler the launching of a sub-Form. For this

button we need the 'NationAddit' window.

===========================================================================================================================================

Okay then guys, it works, even though it needs a bit of cleaning up. Above you see an image of the 'Nation Addit' window

and the title of the Form needs adjusting, amongst a few other things ;-0)

First, before we go to make 'Add & Edit' screens, lets keep improving the 'Games Options' one we have been working on.

Here are some more, and similar results as the previous one, and see we have two new extra images too - to brighten up our lives !

Checkout this code to see what is going on :-

=====================================================================================================================================

Although this is simple enough, the XAML script is not that much more complex either,

Look at the new script in detail - study thoroughly - see below :-

===========================================================================================================================

As I said earlier, not much different, just variable and parameter names etc..

Enough for now, time for a break, see you in a while ................

PHH - 15th. September 2012.


Adding and Saving a new Nation

Okay guys, with our first extra Form for Add & Edit, we will start simple, and also with an object / Table

which does not depend on anything other than an existing Continent - and there are only five of those.

However, we will also experiment with adding Data Sources (DS) to the pane of that name within VS11.

Hopefully, we can develop our skills for dragging DS's from the pane and onto the Designer surface, to save

us lots of work in the future for placing controls conveniently for display and editing purposes.

Fingers crossed ! - let us do some exploring and experimenting to see what is possible.

Making a Start to Create a Data Source :

If you select the Form from the SE pane called 'NationAddit.xaml' and adjust the various screen settings a little,

it may look like mine in the following image - see below :-

==========================================================================================================================================

Notice that top left of image we have the 'Data Sources' (DS) pane, and that it is empty - or without any DSs.

If we click on the 'Add New DS' live wizard link we get the following showing on screen :-

===========================================================================================

I have purposefully selected the 'Object' option in the above Wizard screen.

============================================================================================

I have selected to open 'Olympics2012 and will further open and select from ' {} Olympics2012 ' after

opening it, see below :-

============================================================================================

When you have selected 'Nation' as seen above, press 'Finish' and you will see 'stuff' appear in the

Data Sources pane - mine looks as follows :-

===============================================================================================

Drop the list of options and select 'Details', and your main icon ought to change to show that below :-

==============================================

Now for the BIG experiment, let us now drag the 'Nation' node from the DS pane and onto the Designer surface,

within the Grid of the Form itself :-

=========================================================================================

When we release the mouse 'drag' button we get some controls automatically showing on the Form surface.

Below is what I got, and where they were left 'placed' on the design surface - check this out :-

=================================================================

Later, when we get good at this, we may need or wish to reposition these - but for now either leave them where they

are or 'marquee select' the whole group (as it is above) and use the up and down arrows to move the group of controls around.

Before we leave this aspect of Data Sources, and dragging controls, let us learn an easy way (only one) to 'marquee select'.

In the following image I have used the XAML script text editor, and highlighted the area shown - in fact everything between the

second, or inner, 'Grid' tags. Check this out carefully :-

===========================================================================

Now we need to move the focus to the graphical designer, BUT, without losing the grouping we have created. I tried (with some

success) to click the scroll bar in the top pane (Designer) then this caused my arrow keys to move the controls, rather than work

within the text editor. You may like to give this a go yourself.

Having made a small change to the Form title we see this in the designer surface :-

============================================================================

Okay the guys, some success but time for a think ahead ..............

What have we done, and where are we going from here ? :

To be honest, when I started this section on adding and then using the DS items from the Data Sources pane, it was all a bit

of an experiment.

However, now that we can see just what a chore this approach (or process) can save us by auto making and placing controls

on or Form surface, we may need to go back and see just what the full extent of the dragging of the DS can be as far as giving

us 'easy' controls, and even binding details as well.

For this current exploratory exercise I am quite happy to use the DS 'drag' to give us elements and controls on our surface -

quick and easily - and then edit then and change bindings too.

If we were doing proper MVVM 'stuff' we would first make a suitable new class which would be designed for the Add/Edit (Addit)

Form and then use that directly. We will do that a little later, for now lets just fully explore what the current Nation object can

give us on our screen.

Firstly - remove the existing Controls :

Before we can have a second attempt at dragging a DS onto our design surface, we need to clean up our code and script by

removing stuff previously added automatically by the system by the 'drag' and 'release' process.

First the code - highlight and remove that portion shown in the following image :-

===============================================================================================================================

And now the script - go to the XAML text editor of the 'NationAddit' Form, then highlight and remove the section shown below :-

==============================================================================================================================================

Once this has gone we also need to remove the event from line 9 - see below for details :-

=============================================================================================================

After removing the event, we then need to remove the controls themselves - there are a couple of ways to do this, one (possibly the safest)

is to highlight the XAML script and press the 'del' key.

As shown in the next image, highlight everything between the first (or outer) set of 'Grid' tags - the delete it :-

===========================================================================================================================

Now a BIG test - do a compile and run of the app - hopefully you will see this :-

=====================================================================

Time to move forward ..............

Having a second go with our 'Nation' DS :

Okay then, lets go back to our now empty Designer surface for the 'NationAddit' form.

Below you will see that I have been into the selection options on the various properties and

changes then to be as shown - just so we can do a suitable experiment in a few moments time.

Check this out, it is the same Data Source as we used previously :-

======================================

So then guys, time for the BIG experiment, what do we get when we DnD (Drag and Drop) ?

Here is what I get - study the following image carefully :-

=================================================================================

And after slightly increasing the Forms Window dimensions we see this :-

=========================================================================

Then a test to compile and run, then select with the push Button to get the following :-

======================================================================================

Okay then guys, to complete our little (or BIG even) experiment, we need to add half a line of code which will

bind a list of nation objects returned from our Olympics database to the form and controls we have just put

together so easily.

Check this out below - see line 32 in particular :-

=====================================================================================================================================

And if we compile and run we see the following :-

=====================================================================

Yep! we do have some data, but we are not that bothered about it or the Flag image display.

What we ought to be happy about is how we can so easily link up live data with an auto-generated Form.

Time to have yet another THINK about where we are going ! :

Is it time for my favourite bit ? - 'Top Down Design' ?

Maybe we ought to start with a 'blank canvas' and say what we wish to be able to do with our 'Nation Add &

Edit' screen.

I have done a bit of exploratory coding and such, and what we need amongst other things is something like

shown below, where we can select any existing small flag icon from a drop list, as well as also any large existing

flag image.

However, one big difference is that the flags need to be 'free' of existing national ties - just those currently available

on disk really - with the image showing as well as file name.

Here is a test output - check it out and we will then see how I made it :-

=====================================================================

Okay then, we need something different to above, BUT, it will be instructive to see how we got the above image.

First we need to view the new class of 'FlagSmall' - check this out :-

============================================================================================================

======================================================================================================

=============================================================================================================================

============================================================================================================================

=============================================================================================================================

Also the 'DisplaymemberPath' attribute was removed, for the two above sections.

========================================================================================================================================

This is also the sort of thing we need for new Nation entry - selecting the continent :-

PHH - 16th. September 2012.


TopDown plan - towards MVVM

Since this is essentially a 'walk-through' demonstration of what can be done with CF and WPF data binding etc.,

we need to see more that just the finished product of my labours.

In fact we could say that you need to see some of the pain too - some of the in between bits that go to eventually

forming a more polished product.

Let us first see how we can get from designing, and defining, a new 'Super' class for 'NationAdd' to some controls

on a WPF form.

First we see the 'NationAdd' class - check this out :-

===========================================================================================================================

And the above 'NationAdd' class needs others, called 'SmallFlagFile' and 'LargeFlagFile'.

Here they are, one after the other :-

==================================================================================================

And now the 'Large' version of this :-

===================================================================================================

To start the process of making a new Form, I first added the 'NationAdd' class to the Data Sources pane in a manner we

discussed earlier.

Here is the pane as it looked after 'adding' the new source :-

====================================

Now the bit that saves time for most folks, particularly those new to WPF and XAML - dragging the node entitled

'NationAdd' from the DS pane onto the designer surface.

below I show what it looks like after the drag release, but note it is on a 'test' empty Form, as I have already completed

and tested the full 'NationAddit' form.

Check this out below :-

===============================================================

From this useful and very quick start, I then did some changing - adding and editing - both at the designer graphical surface

as well as the XAML script text editing level.

One thing I have to say to anyone new to XAML is that editing the script directly can be a VERY effective way to work. I find

that I do it a lot, and that it gets fast results too. However, I am not shy to use the Toolbox and the designer either ;-0)

In fact the Designer gets better every new release of Visual Studio, and I think I have seen some nice new features that I

have not had time to fully explore as yet. Maybe a ClickStart (CS) on VS11 is required, it is a while since I did CS stuff on VS.

Below is shown the 'almost' there version of my edited Form - check it out :-

=====================================================================================================================

However do be aware that we have still things to improve before we get to our fully working version.

In the image above you see some script in the XAML editor which came about by adding the push Button controls. Note

that each one was given a Click even by first naming the Buttons, and then double clicking them in the designer surface.

So lets see what else the DS 'drag and release' did for us - see below for the 'Window Loaded' event :-

=================================================================================================================================

Since we are going to do a lot of changing of bits and pieces there is no point in looking at the data binding part

of the 'Window Loaded' even handler - we will see this done suitably in the next section.

Before we leave our screen 'development' subsection, lets look at a closer view of the data selection drop lists :-

====================================================

These will need to have suitable lists of objects bound to them, and also suitable Data Templates created so that we see

the visual information in an acceptable, and suitable, format.

What we will be after is something like the following :-

==========================================

Let us now move on to the next subsection, where we see how to go from an almost 'proof of concept' approach for our

new 'Addit' form, to a suitable working one, which does exactly as we require.

See you in the next section ......................

PHH - 16th. September 2012.


From 'Proof of Concept' to Working Form

For the 'Add Nation' WPF form, let us now make that final step in this 'walk-through' section of building

an interactive form with suitable data building, and a simple facility to save details into the back-end SQL database.

The 'final step' will be to 'wire up' our form controls such that three drop list will allow us to enter all the details required

for a new nation, apart from its name, which we will need to enter in a 'free format' / manual entry manner.

As a bit of a change to building up code and script, let us look first at the final result, and see what it looks like when

working and string test results. Checkout the following image and realise that the red border indicates the limits

of the 'NationAdd' class of object which is partly bound to the form, directly :-

=======================================================================================================================================================

As well as being able to attempt to 'Save' the newly entered nation, a test may also be done previous to saving,

to see if the National Name has been entered previously. Below is a capture of such a test :-

=======================================================

Now it is time for us to see what the 'View-Model' (VM) class looks like. I say 'VM' as we will part move towards the

MVVM approach of having a class (one class of object) which binds to the whole form.

Let us study in detail what this class looks like in code - see below :-

===========================================================================================================================

In the above image you can see the lines 1297-1299 which are the three list which are to be bound to the

drop list controls, outside of the red rectangular boundary.

We see other properties which obviously have a 'one to one' correspondence with the form controls, and also

a couple which are used 'behind the scene' so to speak - these are 1294 and 1295 which hold the filepath strings

for the flag images displayed on screen.

It is unnecessary to have the file strings shown on screen, as to the user, it is the visual form of the flag which is

being selected (along with the three letters of the actual file).

When we use this class in the code for the 'Nation Add & Edit' form we make a 'Window Loaded' event handler

like that shown in the next image - check this out :-

=======================================================================================================

For some reason the red wavy line indicates that intellisense seems to dislike 'AdditMain' even though the

code compiles and runs OK - and - the wavy line does not always go away afterwards!?

I think this must be due to my Beta version of VS11, as this morning when I look at a re-booted system I see this :-

=========================================================================================================

So what does the other end of the data binding look like ? If the above is the 'Code' end, then below is the 'Script' end :-

=====================================================================================

In the above image line 11 of the script shows the 'DataContext' attribute being set-up for binding. When done like this

then we have to supply an association in code.

Let us now move on a pace ..........

The IMPORTANT bits ! :

We could say that the important part of all this is how we eventually 'save' the details which are both entered and selected.

Below is the image of the code which makes up the event handler to the 'Click' event on the 'Save' button.

Because we have not as yet done a 100% MVVM approach, we have to add lines 74/75 into the handler, as opposed

to having binding do everything for us. Well, this was done so that other things were kept as simple as possible.

Checkout the call to the STATIC method in line 78, in particular :-

============================================================================================

Have assigned data vales to our Continent properties we use the following STATIC method to carry out the 'Saving' task.

Now then, we need to remind ourselves that the 'NationAdd' object was just a 'super' object of the 'Nation' class - meaning

that it contained all the properties for 'Nation' as well as the list for the drop list controls.

So the first thing our STATIC method code needs to do is make a 'Nation' class object from the 'Super Nation' object.

Below is how the 'Nation' object is made from the 'NationAdd' object - a mapping really - and the saved using CF technology.

Check this out thoroughly :-

==================================================================================================================

As you can see in the image above, there are only three lines which do the CF 'saving' process.

Lines 230, 234 and 235 are the lines in question. The first of these, 230, makes a CF 'context' object

which is the used in the other two, 234 & 235.

You have to agree, its pretty neat, and simple to do - some would even say its 'cool' ;-)

Now for something a little different, doing a check to see if a nation already is entered in the DB with the same name as

that supplied by the user.

First of all lets see the event handler behind the push Button control on our form :-

=========================================================================================

So it is the method call from line 69 which the all important one,

When we study the details of this STATIC method (called 'NationExists') we will see some more CF technology in

action, along with some LINQ syntax code too - check this out below :-

====================================================================================================================================

[ .. if there had been lots of data rows, we would used a different approach - using 'FirstOrDefault' so that not all rows .. ]

[ .. are searched every time .. ]

Once again, there are only a couple of 'important' lines, and those are 139 -146 in the above image.

Basically the database server is queried to return a list of records (CF makes these a collection of Nation objects) where

the 'NationName' column / property is equal to the name supplied by the user in the free entry text box.

You may be interested to know why we made the method return Nullable, well, it is to handle the case when the default

value has not been changed - it is of no use to the user to be told that '.. change me ..' is not yet a nation !!!

Time to move on.

Other Event Handlers :

Now then, lets look at the handler code for two other events, those when the drop lists (Combo Boxes) are used and

items from the available lists selected.

Because we have chosen to place the drop lists outside of out red border, and bind them to our controls, instead of the

'NationAdd' properties, we need to insert a couple lines which respond to the drop list selection, then assign

data values to certain properties on the 'NationAdd' object.

We need to realise that the MVVM approach is trying to get rid of this style of 'entanglement' - BUT - we can't study all

things at once without stuff getting too complex, and even confusing. So bear with me on this issue ;-)

The two handlers below, create a 'Byte Array' ( byte[] ) from a string value for the 'FilePath' - we will see this STATIC method

in a little while, first we need to see the handlers - check this out :-

=====================================================================================================================================================

As a matter of interest, if we are happy with this approach of using event handlers to our form, as part of the Form

code behind, we could have added another handler and chosen to react to the selection event of the Continents drop list.

In doing things that way we could then have removed lines 74 & 75 in the 'Save' event button click handler.

Without total MVVM its a bit of 'swings and round-a-bouts' really.

Anyway, below are some positive results shown in Management Studio - and as you can see I have made a few tests :-

==============================================================================

So, as you can see above, this code and script does work together to give us what we need, or require.

Now to have a little bit of colourful display ;-)

Below is shown the drop list for the Large Flag images - in action :-

============================================================================================================

Note in the image above the name of the individual files can also help in pinpointing the correct nation. These are

directly from the official Olympic Games 2012 web site.

Time to move on .............

Personal Choice - Handlers :

Before we move on to the next subsection let me say that I prefer to have the event handlers used as shown below.

The 'SaveNew' is as simple as possible, and the setting of 'Continent' related values is done by a 'SelectionChanged'

handler on the 'Continents' drop list - check this out :-

========================================================================================================================================================

Please remember, that if we had made Dependency Properties in our class 'NationAdd' we could have done more work

through data binding, and move closer to the MVVM model.

But to use an older fashion of programming - " It works so it must be OK ! " ;-0)

Time to move to another section, see you there ................

PHH - 18th. September 2012.


Adding and Saving a new Venue

PHH - 15th. September 2012.


Adding and Saving a new Sport

PHH - 15th. September 2012.


Adding and Saving a new Event

PHH - 15th. September 2012.


Adding and Saving a new Athlete

PHH - 15th. September 2012.


Adding and Saving a new Entry

PHH - 15th. September 2012.


Entering Event medal winners

PHH - 15th. September 2012.


Chapter 13 - 'Polishing' the Olympic Games app

PHH - 15th. September 2012.


Finding Information

PHH - 15th. September 2012.


Chapter 14 - Lazy Loading, and other stuff

PHH - 20th. September 2012.


Lazy Loading

PHH - 20th. September 2012.


Eager Loading

PHH - 20th. September 2012.


Explicit Loading

PHH - 20th. September 2012.


Asynchronous coding

PHH - 20th. September 2012.


Chapter 10 -

Chapter 15 - Making Functions and Procedures

PHH - 19th. September 2012.


Example using the Games 2012 application

PHH - 19th. September 2012.


Functions - Scalar and Table

PHH - 19th. September 2012.


Procedures

PHH - 19th. September 2012.


Creating Views

PHH - 19th. September 2012.


Chapter 16 - 'Collections'

I write this next few sentences after doing the work for about 60% of these eNotes, reading the four or five texts

on EF and LINQ and doing lots of exploratory coding and scripting.

I have NOT seen a DataTable (DT) anywhere !!

Previously when I did SQL work with .NET I favoured getting back all my returned data in ADO.NET 'set' and

'DataTable' objects.

It was VERY quick and easy to display a DT in a WPF 'DataGrid' control, and have it 'bound'.

While following Julia Lerman et al we see ONLY 'collections' of custom objects.

So 'collections' are extremely important while working with EF and CF. We simply work with custom objects from

start to finish - throughout our application.

Remember, each 'Entity' is a different 'flavour' of "Data Pipeline" which handles the passage of custom objects - one

or many. Usually, we have collections of objects moving 'to and fro' through the 'pipeline.

The LINQ syntax works with 'collections'.

Short Summary, so far :

'Collections' are so important that we need to become 'Masters' at working with them, in order to get the most from EF.

We need to find out the standard techniques for handling collections, and apply these whenever, and wherever, appropriate.

DataTables and Sets are part of ADO.NET technology, and we no longer develop at a surface where ADO.NET is exposed,

therefore we no longer use DTs or ADO.NET - instead we use Objects, Collections and LINQ query expression syntax.

'Moving Through' & 'Looking At' - Collections :

Most of us are used to 'looping' through arrays, and even ArrayLists.

However, with collections we have some extra tools designed specifically for accessing, and moving through collections.

We need to get VERY familiar with the 'FOREACH' structure, and also master the use of an Enumerator. Both of these

have a subsection later in this chapter.

Make sure you use the very latest, and best of the .NET collection types, so that your development and coding is easy.

WPF and Data Binding :

If as most of us guys, you intend to have GUI in your app, and display and view collections in GUI controls, then make

sure that the objects within your collections have properties defined as Dependency Properties, so that they may be used

in data binding - reflecting all changes, in both directions.

PHH - 20th. September 2012.


Which types to use

It can be VERY confusing while reading existing SDK documentation, and even what appear to be current,

or modern, text books on .NET programming.

What do I mean by this ? well, we seem to have the word 'collection' used widely, and through much of what we read.

We have to remember while doing our reading that some 'stuff' was written well before other 'stuff' - so we have a

historical 'time-line' to interpret as well and getting to grips with the technology.

It would appear that ' List<T> ' is very important to us. This is a generic list of typed objects, so we can have for

example List<Athlete> in our Olympic Games application. So the overall 'object' is a list of 'Athlete' objects, where

the 'Athlete' class is defined by us, within our app.

When it comes to carrying out more complex data binding then the 'ObservableCollection' (OC) is the one to use, as it

tracks changes in the collection objects, and can be instantiated from a List<T> collection type. So these two

types work well together.

In general coding, while dealing with data, the List<T> is the one to use, but when we come to displaying data on

WPF forms, the we need to call on the ObservableCollection' to make sure we get the most from our data binding.

Dependency Properties :

There is another issue which needs to be addressed, and that is DPs or Dependency Properties. If we are to be

able to get the most out of data binding (two ways particularly) we need to define our classes correctly.

By 'correctly' I mean that any property of our custom class which is likely to be used for data binding purposes, MUST

be defined and declared as a Dependency Property.

Binding and Dependency is all about tracking changes made at runtime.

In a lot of what I have done in these eNotes I have not had my custom classes inherit from 'DependencyObject' but

this ought to be done for a real life 'robust' application.

However, before we get carried away, the 'MVVM light' software may do a lot of this stuff for us, so just be aware,

and wait and see :-0)

List<T> versus ArrayList :

Many of us have gotten into the habit of using ArrayList, but I would suggest that you completely STOP using it as

a type, unless you particularly have to.

'ArrayList' is older, and was in .NET first. OCs can't be instantiated from ArrayLists as they can List<T> objects.

PHH - 20th. September 2012.


List<T>

PHH - 20th. September 2012.


ObservableCollection

====================================================================================================================================

=====================================================================================================================================

Constructor - Overloads :

====================================================================================================================================

============================================================================================================================

========================================================================================================================================

PHH - 22nd. September 2012.


FOREACH - foreach

Lets keep this as simple as possible guys.

'foreach' is designed to help us access collection items in a forward 'read only' fashion, and to be as fast as possible.

We had better read what the MSDN documentation has to say on this - see below :-

=========================================================================================================================================

Any returned items from a LINQ query supply us with a suitable collection - as described in line two above, of the first paragraph.

For this reason you will see lots of 'foreach' statements used with Code First and EF.

Let us see one of these in action from our development code for the Olympic Games application :-

[ .. do not worry about the SQL query, we are using a 'View' and not a Table via an Entity .. ]

====================================================================================================================================

In the above image you will see that we use ' var ' in place of a specific data / class type. This is extremely common

practise when coding for LINQ - and for those who don't know it, the ' var ' mean take the Type of the objects in the typed collection.

So in the above example the 'FA' in the 'foreach' structure will be of type 'AthleteFull'.

Obviously, the nice things for us who code, is that the intellisense shows all the available properties on the collection item class

and this can be seen demonstrated in the following image :-

=================================================================================

And now checking the bottom of the drop list options we see the following :-

===================================================

The results of the ' foreach ' as it is shown above are as follows :-

======================================================

But when we explore the use of ' continue ' we see that this code works, see below :-

======================================================================================================================

And when we explore the use of ' break ' we see that we do as in the next image, shown below :-

==================================================================================================================

So to summarize, we can use ' foreach ' to access our collection items by moving through them - start to finish - and

we can skip to the next item, and also stop the iteration if we so wish, using a condition.

List<T> works just fine :

Just in case you are new to this stuff, or are worrying about the term 'collection', when you are using a List<T>, then

stop worrying.

The following example shows that a generic 'List' is a collection in all senses of the word - check this out :-

====================================================================================================================================

We now need to do something to show that we have changed types by going from 'FullAs' to 'OurList', so

you had better check out the following images carefully :-

=======================================================================================================================================================

So we see we have gone from 'IEnumerable' to 'List'.

Where from here ? :

Well then guys, seeing that the next subsection is about 'Enumerators' we had best read and study the following image

of a remarks in the MSDN eNotes on Enumerator etc. - check this out :-

========================================================================================================================================

So at this point we had better move on to see more of the details on Enumerators.

See you in the next subsection ..........................

PHH - 20th. September 2012.


Enumerators

========================================================================================================================================

We need to follow up about being 'synchronized !

=============================================================================================

======================================================================================================================================

ObservableCollection :

==================================================================================================================================

============================================================================================================================

PHH - 20th. September 2012.


Chapter 17 - Advanced CF - 'Views' and stuff

PHH - 21st. September 2012.


using an SQL 'View' as a Table

PHH - 21st. September 2012.


ways to Create a 'View'

============================================================================

========================================================================

=======================================================================

===================================================================

==============================================

=====================================================================

=============================================================================================================================================================================================

==========================================================================================

============================================================================

==============================================================================

==================================================================================================================================================================================================================

==================================================================================

============================================================================================================================================

[ .. Note column name change in View to 'SportName' .. ]

=================================================================

=========================================================================================================================

============================================================================================================================================================

Creating the 'View' directly from code :

Both ALTER and CREATE work for 'Views'.

==================================================================================================================================

PHH - 21st. September 2012.


Chapter 19 - Visual Studio 2012, 'Explored'

when using Win8 we get .NET 4.5 and Metro / Modern.

better designer support for XAML and Blend integration

better support for SQL Server use - panes and facilities

Data Sources pane - make a DS from a custom object, drag and drop on WPF and WinForm surface

controls drawn and binding done too.

PHH - 20th. September 2012.


Getting Started with VS11

PHH - 20th. September 2012.


VS11 on a Win 7 platform

PHH - 20th. September 2012.


Facilities for 'SQL Server' access

PHH - 20th. September 2012.


Data Sources pane - facilities and use

PHH - 20th. September 2012.


WinForms - Data Source and Data Binding

PHH - 20th. September 2012.


WPF - Data Source and Data Binding

PHH - 21st. September 2012.


Server Explorer - browser pane

PHH - 21st. September 2012.


SQL Server Object Explorer - browser pane

PHH - 21st. September 2012.


Seeing and Editing table data

==========================================================================

===================================================================

PHH - 21st. September 2012.


MVVM light

PHH - 20th. September 2012.


Appendix A -

Appendix A - Tips and Tricks

Relative paths in VS project / solution :-

===========================================================================================================

To over-rule the 'Escape' style interpretation of a string use the '@' prefix as seen above.

ToList() - so don't re-query, but is being tracked.

Use Auto Mapper to get an object FREE of tracking.

Formatting Dates and Times - directly in XAML script :

First the date options :

The first of these three alternatives are shown working in Chapter 8, "Getting back Athlete information."

This one shown below is probably better in this case - see the next two images :-

================================================================================================

===================================================

And now a look at a couple of Time options, where the Date is not shown.

This may be the most useful, and that is why it is the simple default for 't' :-

================================================================================

Which produces the following output - see below :-

=====================================================

And now something less useful perhaps, check this out :-

================================================================================

Which gives the following output :-

==================================================

===================================================================================

====================================================

============================================================================================

================================================

PHH - 23rd. August 2012.


Optimisations

I have just come across this web article while doing some work on Metro.

It has some VERY useful points to conside when doing EF and LINQ.

https://rahulgbhatia.wordpress.com/2013/03/12/tips-to-improve-entity-framework-performance/

Thanks to Rahul !

=======================================================================================================================

PHH - 14th. March 2013.


Appendix B -

Appendix B - 'gotchas'

the constraint issue with slightly more complex PK to FK setups.

ToList() - extension method - puts an object in the cache, but this is still being tracked for changes.

As long as the object remains in scope it would seem.

PHH - 23rd. August 2012.


Appendix C -

Appendix C - Dependency Objects

PHH - 23rd. August 2012.


Appendix D -

Appendix D - 'Entity SQL'

Although we will be looking to use 'LINQ to Entities' for all or most of our querying with EF apps, we may as well know about

'Entity SQL' - for our interest and education, and knowledge of history, as much as anything.

Here is what Julia Lerman has to say in her learned text book (second edition) :-

=========================================================================================================================

===========================================================================================================

==============================================================================================================

======================================================================================================================

===================================================================================================================================

Well, its a bit tricky getting the right type of object returned, but I am sure with some more practise and doing some

research into the MSD docs we could get reasonably competent.

For the working example above I got this to work after some trial and error ;-)

Here is what Julia says about the anatomy of the Select / From clauses :-

=================================================================

I suggest you read more from her book on this, and I recommend the eBook format. I am using the PDF format.

===========================================================================================================================================

==================================================================================================================

=======================================================================================================================

================================================================================================================================================

============================================================================================================================

================================================================================================================================

PHH - 24th. August 2012.


Appendix E - connections

======================================================================================================================

=====================================================================================================================================

We can use this directly in the Back-Up STATIC method in place of a hard coded string.

PHH - 25th. August 2012.


Appendix F - mapping, SQL data types to .NET

Most of this stuff is well known but Julia puts together a nice table :-

PHH - 30th. August 2012.


Appendix G - 'Fluent API'

PHH - 9th. September 2012.


Appendix H - 'Auto Mapper'

https://github.com/AutoMapper/AutoMapper/wiki/Getting-started

PHH - 11th. September 2012.


Appendix I -

Code First and 'DbContext' :

The concept of 'Lazy Loading' and when we may need to use it - or not - is probably something we all wish

to leave until later when we first come to EF4 and Code First.

However, we need to record the syntax which works for us when we do need to take this up for real !

Below is what compiles and works for me here with VS11 and Win8 :-

=================================================================================

Other 'Configuration' options are shown in the following image :-

====================================================================================================================================================

Maybe we ought to note for each setting what the default is, and possibly for other settings too.

PHH - 13th. September 2012.


Appendix J - Back-up DB from 'context'

 Top Previous

===================================================================================================================================================================

=====================================================================

Testing the "BackUp" facility :

=========================================================================================================================================

Final form - with improvements :

==================================================================================================================================================

================================================================================================================================

=====================================================================================================================================

Get the 'Catalog' string from existing objects rather than have it hard code as above.

Check this out :-

=====================================================================================================================================

Putting this all together we get the following STATIC method for making 'BackUps'.

=================================================================================================================================================

Here is a live test - or its results ;-0)

===========================================================================================================================================

Yep! today is the 21st. September.

PHH - 19th. September 2012.