How can I create and use views using EF6 Code First? - stored-procedures

Is there actually any official strategy for creating and using views with EF6.1 Code First? I can reverse the database into Code First and get tables not views. I can import the database into Model First and get views and then do Generate DB from Model and my edmx is modified and the views are converted to tables. MSFT seems to have all but abandoned Model First, and the new Update 2 seems to have reverse engineering for Code First so I feel forced to convert to Code First but has the EF team given support for any reasonable approach to using views or stored Procedures in Code First? After all CF is supposed to create the DB but what - are you no longer supposed to use either of these SQL Server features in a .NET EF application?

For starters you can use views and stored procedures that are already created in the database. For views you don't have to do any mapping if you create a code like this:
public TestContext : DbContext
{
public DbSet<User> AdminUsers { get; set; }
}
And you have a view in the database named dbo.AdminUsers and it can be mapped to the class User (contains all required properties with the same name as the property).
For stored procedures you can use the SqlQuery function either through the Database property of the DbContext such as:
var userActivityReport = context.Database.SqlQuery<UserActivityReport>(
"dbo.GetUserActivityReport #p0, #p1", startDate, endDate);
Or through the SqlQuery function of the DbSet class:
var newUsers = context.Users.SqlQuery("dbo.GetNewUsers #p0", count);
If you want to create, modify or delete views and stored procedures via Entity Framework you can either use custom migration operations see http://dolinkamark.wordpress.com/2014/05/03/creating-a-custom-migration-operation-in-entity-framework/
For event better integration you can use the Public mapping API with a library provided by a community member: https://codefirstfunctions.codeplex.com/

Related

EF4 database first configurable schema

I have one issue I am trying to resolve for days now, but I can’t get the right approach.
I am using EF4 and I have one application where I use DataBase First, which originally created the ObjectContext, and I donwloaded the DbContext generator and generated it.
The thing is, I need the application to be able to get the database SCHEMA from some configuration file, instead of ALWAYS using the “dbo” default.
I was trying to use the “ToTable” method (so I can specify the schema) in the “OnModelCreating” overload method but as this article sais, as I am using DataBase First, that method is not called.
How can I make the schema name configurable?
Is that even possible?
I read this article too, where it says I can combine database first with code first but I can’t see how to do that if I can’t use the "OnModelCreating" method.
Thanks a lot in advance!!!
I don't know about configuring schema. However if you want your db first approach to changed to the code first, just change the string parameter of your DbContext constructor.
Suppose that you have the following DbContext that EF Db first created for you:
public class MyDbContext : DbContext
{
public MyDbContext()
: base("Name=DefaultConnection")
{
}
// DbSets ...
}
change that to the following to start using code first and all magic tools of it (migration, etc.):
public class MyDbContext : DbContext
{
public MyDbContext()
: base("YourDbFileName")
{
}
// DbSets ...
}
It causes that EF creates a new connection string using SQL Express on your local machine in your web.config file with the name YourDbFileName, something just like the early DefaultConnection Db first created.
All you may need to continue your way, is that edit the YourDbFileName ConStr according to your server and other options.

Entity Framework 4.1 - Code First with existing Database, how to define classes, using Attributes or EntityTypeConfiguration? What is the difference?

I have been studying the EF for a short time and cant find the answer to this question.
I have existing database and I am using CodeFirst to create classes for the model.
What is the difference in using Attributes and EntityTypeConfiguration to define parameters of table columns?
Since the database already has defined foreign keys and unique constraints, and so on, how and where to implement the validation for a best and most fluid result for use in ASP.NET MVC3?
Is it better to implement Attributes and CustomValidation or to use TryCatch blocks to catch errors from db?
Does Validator.TryValidateObject(myModelObject, context, results, true); use validation rules defined only as Attributes or can it use rules defined in EntityTypeConfiguration?
Thank You
Get the Entity Framework Power Tools CTP1 and it will reverse engineer your database and create entities, and a full data mapping. This is different than Model or Database first in that it generates a fluent model rather than using an .edmx file. You can see exactly how it works then.
See the following article about how you can create your entity classes from existing database :
http://blogs.msdn.com/b/adonet/archive/2011/03/15/ef-4-1-model-amp-database-first-walkthrough.aspx
Code generation templates will do the work for you, you don't need to write them if you have an existing db.
For validation, you can create new partial classes under the same namespace and put DataAnottations for your properties. Here is an example for you :
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
namespace TugberkUgurlu.App1.DataAccess.SqlServer {
[MetadataType(typeof(Country.MetaData))]
public partial class Country {
private class MetaData {
[Required]
[StringLength(50)]
[DisplayName("Name of Country")]
public string CountryName { get; set; }
[Required]
[StringLength(5)]
[DisplayName("ISO 3166 Code of Country")]
public string CountryISO3166Code { get; set; }
[DisplayName("Is Country Approved?")]
public string IsApproved { get; set; }
}
}
}
-Since the database already has defined foreign keys and unique constraints, and so on, how and where to implement the validation for a best and most fluid result for use in ASP.NET MVC3?
These should happen via your generated model. Keys are automatically inferred. If you reverse engineer an existing database the attributes will be created for you. If not, there are basic rules that are followed. The entity framework will attempt to use an auto incrementing primary key for example unless you tell it otherwise via
[DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.None)]
The relationships are already part of your model so there is your referential integrity, and the data annotations will define the validation rules.
-Is it better to implement Attributes and CustomValidation or to use TryCatch blocks to catch errors from db?
Implement attributes. Define your metadata classes with your attributes in them.
In addition you want to catch any db errors for anything else that is unexpected if your db has additional logic in there not defined in your model (try catch at some level should generally be used anyways for logging purposes_
-Does Validator.TryValidateObject(myModelObject, context, results, true); use validation rules defined only as Attributes or can it use rules defined in EntityTypeConfiguration?
As far as I'm aware only the attributes are used. I'm going to try to test this later though as I'd like a definite answer on this as well :)

MVC3 Validation with Entity Framework Model/Database First

I want to use MVC 3 and the Entity Framework for my application.
The model will be stored in a different assembly to the MVC app.
The choice I'm making is either to use the EF to generate my entities or to use code first.
With code first, I can decorate members with [Required] etc... But how would I go about adding those attributes if EF has generated entities from the DB?
Having EF generate my entities will save a lot of time, but I want MVC to auto populate the validation depending on how I've decorated my members. Does this make sense? If so, how would I do that?
In that case, MetadataTypeAttribute is used. You can combine it with partial classes to achieve desired results
And by the way, in your place i would do more research when deciding between using Database First and Code First designs. That all is not about saving time when generating entities, there's much more difference between those two approaches. For the time saving purpose, you can use EF Power Tools to generate code first entities from database - simple.
Better than auto generating your entities, I recommend you to use Code First or mapping an existing database to POCO's classes (not generating the entities, just creating them by hand and mapping them to the existing database)
Scottgu wrote about using EF "Code First" with an existing database.
Check this out:
In your model template (file with extension model.tt) you can hack this template for generating decorators, in this example I add the [Required] decorator plus an error message
var simpleProperties = typeMapper.GetSimpleProperties(entity);
if (simpleProperties.Any())
{
foreach (var edmProperty in simpleProperties)
{
if(!edmProperty.Nullable)
{#>
[Required(ErrorMessage="<#=String.Format("The field {0} is required",edmProperty.ToString())#>")]<#
}#>
<#=codeStringGenerator.Property(edmProperty)#><#
}
}
So the result is something like this
[Required(ErrorMessage="The field Id is required")]
public long Id { get; set; }
PS: You can also add the
using System.ComponentModel.DataAnnotations; by editing the template.
Hope this can help you up.

Change model after database is created on EF4 code only

Hey, sorry for my bad english...
Using EF4 code-only, I have created some POCO classes and my database was generated from that. All worked fine, I inserted some data on the tables but now I need to create a new property on one of my classes. If i just create it, the application give me the exception:
{"The model backing the 'TestContext' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance. For example, the RecreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data."}
I tried to create manually the field on the table, but it is still complaining... does someone know if there is a way and if so how can I manually update the database schema (i don't want to recreate it because i already have data) to match the model?
It should work if you make sure that your new column match exactly your new property.
For example, if you add a property NewProp
public class MyEntity
{
[Key]
public int Id;
public string PropA;
public int PropB;
public int NewProp;
}
then in your database table MyEntities, you would add a column NewProp of type int not null.
What you can do to check if the column you add is correct, is to rename your database, then let Code-First recreate the database and see what's different between the original and new databases.
EF generates partial classes. So you can add new properties(fields) in another partial class.

LINQ Modelling Automagically Retrieving Data Via EntityRef

I'm using LINQ to model my database, but I'm writing it by hand (Steve Sanderson recommends this in his ASP.NET MVC book). What I need to know is what's happening when you create an EntityRef, and how it's referenced. If I create my queries manually (without using LINQ), but use LINQ to model it, and I bring back just the ID of something, then reference the actual table column using EntityRef in the view, does it do the join, or does it re-query the database for that bit of information?
To clear things up, if I have this in my repository:
public IEnumerable<MyTable> ListMyTable(int? myColumnVar)
{
string query = "SELECT * FROM MyTable WHERE MyColumn = {0}";
return this.ExecuteQuery<MyTable>(query, myColumnVar);
}
and then in my controller I do this:
IEnumerable<MyTable> mytables = _contractsControlService.ListMyTable(1);
return View(mytables);
then in my view I do things like
<%=tbl.Ref.MyColumn %>
I'm referencing something set out by the LINQ model, but isn't actually in the table output. How does it get that data?
To clear things up further, we're using systems which require ultimate speed, so the LINQ-to-SQL is too slow for us, hence why we're using direct queries in our repository. I wouldn't mind using this EntityRef business if only I knew what was happening underneath.
You have most likely used the Object Relational designer to create an entity class for the Ref entity and an association between the MyTable and the Ref entity. You can also do that manually by creating the appropriate entity classes and using attributes to map the classes to the database schema. You can read the details in How to: Customize Entity Classes by Using the Code Editor (LINQ to SQL) on MSDN.
In your generated (or handwritten) code you will find some attributes:
[Table(Name="dbo.Ref")]
public partial class Ref : INotifyPropertyChanging, INotifyPropertyChanged
and
public partial class MyTable: INotifyPropertyChanging, INotifyPropertyChanged
{
[Association(Name="Ref_MyTable", Storage="_Ref", ThisKey="RefId",
OtherKey="Id", IsForeignKey=true)]
public Ref Ref
{
get
...
The entity classes combined with the attributes enables the Linq-to-Sql framework to retrieve entity classes directly from the database.
If you want to monitor the SQL genereated by Linq-to-Sql you can assign the DataContext.Log property:
context.Log = Console.Out;
In your example, navigating from MyTable to Ref, probably generates SQL along these lines:
SELECT Id, Field1, Field2, Field3
FROM Ref
WHERE Id = #RefId

Resources