Entity Framework: Stored Procedure – Function import

How to…get a stored procedure from SQL and use it in code
In this case execute only, not entity CRUD

  1. Model Browser 
  2. Stored Procedure
  3. Right-click
  4. Update Model from database
  5. Get your stored procedure
  6. However at this point still unusable in code
  7. Not obvious step > Double click Stored Procedure
  8. Choose function import options
  9. OK creates function import which is then useable in code
  10. Note all parameters are surpisingly nullable – May be there is a way preventing this. Unsolved

 

Enjoy !

Entity Framework: WinForms databinding in EF4.1 – DBSet

Solved

Dim context As New SOPEntities
System.Data.Entity.DbExtensions.Load(context.Employees.Where(Function(f) f.Current = True).OrderBy(Function(g) g.FullName))
EmployeeBindingSource.DataSource = context.Employees.Local
ListBox1.DataSource = System.Data.Entity.DbExtensions.Tobindinglist(context.Employees.Local)
ListBox1.DisplayMember = “FullName”

Problem

‘local’ is not a member of ‘System.Data.Objects.ObjectSet(Of <entityname>)’

See http://wp.me/p17IS4-ih

 

Solved

Open the <Name>Model.edmx > Right click > Add code generation item…

Choose ADO.Net DbContext Generator. This has affect of changing the .edmx file Code Generation Strategy to “None” and creates a text template model and .Local now works.

Discussion

Uses EF4.1 EntityFramework.dll
Database first, then add code generation item to get T4 simpler classes and DBSet inherits DBContext
Initially could not work out how to get the Load method. See above for solution.
There is no MSDN VB.Net sample yet. The C# is more like context.Employees.Local.ToBindingList. So it took me a while to work out the syntax above.

Unsolved:
Also the FullName is now a computed column in the database. Was unable to work out how to do this in EF. It may come in the future as a “Model Defined Function”. Do not think this is a Scalar or Complex Type which is something else.
Unsolved:
For BindingSource to support complex filter it needs to support IBindingListView. Typically EF does not.

Links

Binding Objects to Controls
http://msdn.microsoft.com/en-us/library/gg197521(v=VS.103).aspx

Following is in C#
http://msdn.microsoft.com/en-us/library/gg197523(v=VS.103).aspx

Transact SQL: Dynamic Pivot

Normal pivot in SQL means pre-defining the pivot column output, unlike Excel which dynamically works out the pivot columns.
A solution to this was found here with thanks to:  http://sqlserver-qa.net/blogs/t-sql/archive/2008/08/27/4809.aspx This copied after comments below with my own naming again here.

Comments

I wanted to join the data from this dynamic pivot to other data relating to the item and for one parameter (ProductID). I created a stored procedure which created a dynamic SQL including these columns and the parameter and passed this SQL to the generic dbo.uspDynamicPivot.

Dynamic PIVOT in SQL Server 2005

The PIVOT operator available in SQL Server 2005 is used to generate the Cross-tab results. Consider this example

select * from
(
    selectYear(OrderDate)as pivot_col,e.lastname, o.OrderDate FROM northwind..Employees as e
    INNERJOIN northwind..Orders as o ON(e.EmployeeID=o.EmployeeID)
) as t
pivot
(
   
Count(OrderDate)for pivot_col in([1996],[1997])
)
as p

which shows total orders of each employees for years 1996 and 1997

What if we want to have this for all the years available in the table
You need to use dynamic sql

This procedure is used to generate Dynamic Pivot results
The approach is very similar to my Dynamic Crosstab with multiple PIVOT Columns blog post

create proceduredbo.uspDynamicPivot
(
@select varchar(2000),
@PivotCol varchar(100),
@Summaries
varchar(100)
)
as

declare

@pivot varchar(max), @sql varchar(max)
select @select =replace(@select,‘select ‘,‘select ‘+@PivotCol+‘ as pivot_col,’)
 

createtable #pivot_columns (pivot_column varchar(100))

Select

@sql=‘select distinct pivot_col from (‘+@select+‘) as t’

insert

into #pivot_columns
exec(@sql)

select

@pivot=coalesce(@pivot+‘,’,)+‘[‘+pivot_column+‘]’from #pivot_columns

select

@sql=

    select * from 
    (
        ‘
+@select+
    ) as t
pivot 
    (
        ‘
+@Summaries+‘ for pivot_col in (‘+@pivot+‘)
    ) as p
exec(@sql)
 Purpose : Find total sales made by each employee for each year
Usage :

EXEC

dynamic_pivot
‘SELECT e.lastname, o.OrderDate FROM northwind..Employees as e
INNER JOIN northwind..Orders as o ON (e.EmployeeID=o.EmployeeID) ‘
,
‘Year(OrderDate)’,
‘Count(OrderDate)’

Purpose : Find total sales made by each company for each product

Usage :

EXEC

dynamic_pivot
‘SELECT s.companyname,coalesce(od.unitprice*od.quantity ,0) as total_cost FROM northwind..products as p
inner join northwind..[order details] as od on p.productid=od.productid
inner join northwind..suppliers as s on p.supplierid=s.supplierid’
,
‘productname’,

‘sum(total_cost)’

Published Wednesday, August 27, 2008 12:58 PM by Madhivanan

Entity Framework: Generating Strongly Typed Entity Classes: Lightweight

Lightweight

Step by step here: http://msdn.microsoft.com/en-us/data/gg685494

Videos here:  http://msdn.microsoft.com/en-us/data/aa937723

How to remove serer name items from history of sql server management studio

 

http://stackoverflow.com/questions/1059105/how-to-remove-server-name-items-from-history-of-sql-server-management-studio

For SQL 2005, delete the file:

C:\Documents and Settings\<USER>\Application Data\Microsoft\Microsoft SQL Server\90\Tools\Shell\mru.dat

For SQL 2008, the file location, format and name changed:

C:\Documents and Settings\<USER>\Application Data\Microsoft\Microsoft SQL Server\100\Tools\Shell\SqlStudio.bin

How to clear the list:

  1. Shut down all instances of SSMS
  2. Delete/Rename the file
  3. Open SSMS

This request is registered on Microsoft Connect

https://connect.microsoft.com/SQLServer/feedback/details/424800/ssms-expose-connect-to-server-mru-list-to-users

 

Microsoft Office Excel: “Change startup workbook” and “Create Templates”

Save As > Book.xltx
Change type to Template >
Save in C:\Program Files (x86)\Microsoft Office\Office14\XLSTART

http://office.microsoft.com/en-us/excel-help/customize-how-excel-starts-HP005199391.aspx

How do I .. help by giving user feedback

 

Activities which help include:

  1. Regular email communication: Even if no problems, then report all going well.
  2. How to describe where you are:
    1. Ideally with a picture
    2. Otherwise describe program being used > form being used >
  3. How to describe your issue:
    1. Name the reference being activated
    2. Was it working before
  4. Self-rescue
    1. Has other work on the same form worked today
    2. Are there other problems – network – power
    3. Have you got the latest version of the program
    4. Does it work with only some of the data – you may be able to deduce the particular data which the program is not handling

Entity Framework “Update Model from Database” generates unexpected self-reference associations / navigation properties

EF4.1 Entity Framework “Update Model from Database” generates unexpected self-reference associations / navigation properties

Check in SQL server on the table design, if a relationship started to be formed, but was not completed then it may be left on the table. Removing this unnecessary relationship and then using “Update Model from Database” will remove these extra associations

Entity Framework: Error 111: Properties referred by the Principal Role…

The following error message may contain entity name or other project specific text

Error 111: Properties referred by the Principal Role must be exactly identical to the key of the EntityType referred to by the Principal Role in the relationship constraint for Relationship . Make sure all the key properties are specified in the Principal Role.

Solution upgarde to EF4.1 or higher.

 

Visual Studio Report Designer: Using External Image

Add a table > Link table to a datasource
> Put an image in a cell.
> Image > Properties >
    > “Select the Image Source” to “External”
    > “Use this image” > set to a data source field
> Your Form > Report Viewer > Local Report >Enable External Images > “True”

Example of file names passed:
file:\\ServerName\Directory\SubDirectory\Filename.jpg

see
http://en.wikipedia.org/wiki/File_URI_scheme

but beware of “Percent-encoding” special characters, which include # and others

http://en.wikipedia.org/wiki/Percent-encoding

so ABC#123.jpg will become ABC%23123.jpg