I have a view in my database called "viewUsers" that I need to operate on with my other entity generated tables. How can I retrieve this database view in entity?
In the Wizard, you can select Views. EF will take care of rest. Detailed example here
EDIT : As per the comment (how to do it in codefirst),
As of Entity Framework 4.2, Codefirst has built in support only for tables. That means It is only capable of generating schemas that contains tables. But If you are working with an existing database, You can map a an Updatable View with an entity. You can use the entity framework to select, insert, update and delete data. This works same as of a table. Since the SQL syntax is same for table and view for these operations, we are telling a lie to codefirst tha the view is a table!
Ex : IF we want to get data from a View called vwCustomerDetails for the Entity called CustomerDetail, We can do like this with Data Annotations
[Table("vwCustomerDetails")]
public class CustomerDetail
{
// properties
}
Alternatively, With Fluent API, you can do this,
modelBuilder.Entity<CustomerDetail>().ToTable("vwCustomerDetails");
Loading Data From a Normal View
Sometime you may want to load some data from another view which returns the same result as of our initial fake table (the view). Ex : In some Page we need to show the top Ten CustomerDetails who scored highest points. Assume we have a separate View called vwTop10Customers for that. we can use the SqlQuery method on DBSet to load the entotues like this
var topCustomers=dbContext.CustomerDetails.SqlQuery("SELECT * FROM vwTop10Customers");
The View Must return the exact same column names as of the Entity. Otherwise EF will have a problem for mapping that.
Related
We have a synchronization framework that uses a global SyncEntity table to keep track of which entities have been updated at what time, meaning we have a global table with a structure something like this:
<dbo.SyncEntity>
ID int
EntityType int
EntityGuid uniqueidentifier
The EntityType is an enum that corresponds to the specific entity so that we know in which table to look for this entity.
All our tables have an ID (PK) and a GUID.
I have created a Foreign Key constraint from the different Entity tables and to the EntityGuid in the SyncEntity table.
This works perfect for existing data however when we use EntityFramework to insert new data it doesnt insert the data in the "correct" order resulting in an error because the SyncEntity with the required EntityGuid is not yet inserted.
I guess we could add a property SyncEntity on all of our entities however i really dont want to pollute our domain model with that property.
So my question, is there anyway to ensure that specific Entity types are inserted as the first entities?
Or is there anyway to map the relation from Guid (on the specific Entity) to EntityGuid (on SyncEntity) without a navigation property.
I see two ways you could potentially alleviate this issue.
First, you could use domain events to recognize that a new entity has been created and raise an event, passing in the entity itself as a parameter and then allow that event to create a new SyncEntity insert it and then save it. This will populate your ID and then you can assign it to the new entity creating the relationship.
Second, you could override the SaveChanges method of the DbContext to look at added entities and then create a new record for each of them, then assign your new SyncEntity Ids to the entity.
WHy would you bother EF with something like that?
Have the SyncEntity entry created by a trigger on the tables. Finished. EF does not have to bother with it.
And it is save for direct SQL usage, too.
EF is a good tool - though only a very very mediocre ORM. But it is not a solution for everything. DB internal logic, like a logging table, should be handled in the database.
I am about to begin a web application where I would like to use the Entity Framework with (mostly) code first models.
However, in addition to the application-specific models I plan to create, I have to use an external user database. Is it possible to specify one of my models as database first and to use a separate database context?
Technically, it's possible, but I wouldn't recommend it. It's far better to just use code-first across the board. Yes, ironically, you can use "code-first" with an existing database.
Just create POCOs that match the tables in your existing database. If your POCO is not named the same as your table (not all table names would be valid or appropriate class names), you can use the Table attribute to explicitly tell EF what table your POCO works with:
[Table("SomeTable")]
public class MyAwesomeEntity
{
...
}
Then, you'll need a separate context specifically for this existing database and any entities that belong to it. All you have to do is 1) tell it what connection string it should use and 2) turn off database initialization, so EF doesn't try to actually create the database.
public MyExistingDatabaseContext : DbContext
{
public MyExistingDatabaseContext()
: base("MyExistingDatabaseConnectionStringName")
{
Database.SetInitializer<MyExistingDatabaseContext>(null);
}
// DbSets here
}
And that's it. Whenever you need to work with an entity from this existing database, just new up this context or get it some other way, such as through a DI (dependency injection) container, and go to town.
You should use the code first from database option if you already have an existing database available but want to use code first.
1) In your Models folder, right click on Add, New item,
2) Select ADO.NET Entity Data Model in the Data tab.
3) Enter a model name,
4) Select Code First from database.
5) Select connection string,
6) Choose your database objects you want to include in your model.
You don't have to write the code for the context and model from scratch because it will generate the classes for you.
I have a design question related to Entity Framework entities.
I have created the following entity:
public class SomeEntity {
// full review details here
}
This entity has as an example 30 columns. When I need to create a new entity this works great. I have all of the required fields in order to insert into the database.
I have a few places in my app where I need to display some tabular data with some of the fields from SomeEntity, but I don't need all 30 columns, maybe only 2 or 3 columns.
Do I create an entirely new entity that has only the fields I need (which maps to the same table as SomeEntity, but only retrieves the column I want?)
Or does it make more sense to create a domain class (like PartialEntity) and write a query like this:
var partialObjects = from e in db.SomeEntities
select new PartialEntity { Column1 = e.Column1, Column2 = e.Column2 };
I am not sure what the appropriate way to do this type of thing. Is it a bad idea to have two entities that map to the same table/columns? I would never actually need the ability to create a PartialEntity and save it to the database, because it wouldn't have all of the fields that are required.
Your first approach is not possible. EF doesn't support multiple entities mapped to the same table (except some special cases like TPH inheritance or table splitting).
The second case is common scenario. You will create view model for your UI and either project your entity to view model directly in query (it will pass from DB only columns you project) or you will query whole entity and make conversion to view model in your application code (for example by AutoMapper as #Fernando mentioned).
If you are using EDMX file for mapping (I guess you don't because you mentioned ef-code-first) you can use third approach which takes part from both mentioned approaches. That approach defines QueryView - it is EF based view on the mapped entity which behaves as a new read only entity. Generally it is reusable projection stored directly in mapping.
What you proposed as a first solution is the "View model paradigm", where you create a class for the sole purpose of being the model of a view to retrieve data and then map it to the model class. You can use AutoMapper to map the values. Here's an article on how to apply this.
You could create a generic property filter method that takes in an object instance, and you pass in a string array of column names, and this method would return a dynamic object with only the columns you want.
I think it would add unnecessary complexity to your model to add a second entity based on the same data structure. I honestly don't see the problem in having a single entity for updating\editing\viewing. If you insist on separating the access to SomeEntity, you could have a database view: i.e. SomeEntityView, and create a separate entity based on that.
I have an MVC application in which i need to add the table dynamically i.e table name is prepared dynamically. Is there any way we can check for the existence of a table and if not exist then add it in entity model.
If we can are able to create the table then how we can access the dynamically created table name using the object of entity model?
No. If you want to use new table in EF you also need related entity (class), mapping and ObjectSet exposed in your context. Here you have some ideas what does it mean to use "dynamic" approach in EF.
Why not create a KeyValuePair<MyTableProperties, List<MyObjects>> in the controller, or viewmodel for that matter, then make a strongly typed view and create the table in there depending of the value of the keyvaluepair object.
Or are you talking about some other sort of table?
I am trying to use EF with an existing DB. I brought in a Client table into my data model and let EF create a Client entity. I have a sproc, GetClientSearch, that only returns 5 out of the 15 columns from the Client table becuase that is all that is needed for that call.
Here's what I've done so far:
Added the sproc to Function Imports and set the proc to map to the Client entity.
When I execute the proc through the Context, I get "The data reader is incompatible with the specified 'GAINABSModel.Client'. A member of the type, 'MiddleInitial', does not have a corresponding column in the data reader with the same name." exception. (MiddleInitial is not one of the columns returned in the proc)
I know that I can create a new entity that maps to the proc, but I don't want to do that for every proc I have to import into my model.
Given that the DB is currently in use in production, changing stored procs to map to my current entities may not be an option.
Currently using EF 4 and VS 2010.
So, is there a way to map the results of the sproc to the Client entity, even though the columns returned are not 1:1 with the properties of the EF entity?
Yep, one of my many pain points in EF.
If you can't modify the SP's, your best bet might be to create "wrapper" SP's on top of the existing SP's.
In other words, EF-serving SP's that call into the existing ones, and return NULL for the columns you don't need, but are required for the entity.
Of course the better option would be to create the entities properly.
Another option is to use ObjectContext.Translate<T>, which basically performs a L-R between the SPROC results and the entity you supply.
If the result set doesn't contain the field, then the property on the object will be null.
Which is probably what you want.
Am running into the same Issues. Suppose i have UserEntity created out of the User Table and have 3 procedures.
AuthenticateUser - returns 4 columns from the user table after authentication
RetriveUser - Returns 10 columns from the user table
GetUserName - return UserID and UserName only for dropdown purpose.
If we create different entities for each of the different SP. It would result in bad design because of duplication.
I have no other way of using same entity for all these SP's.
Overall, i don't recommend entity framework atleast for legacy applications in production.(where you can not update your Sp's also.)