Add table dynamically in Entity framework in MVC - c#

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?

Related

Code First Entity that doesn't include some required columns?

I'm trying to use EF6 Code First to map Domain Entities to a legacy SQL database. I do not have access to modify the schema of the database or create stored procedures. The table I'm trying to map contains a few required columns that I don't want cluttering up my Domain Entities, since they aren't relevant to my program (but they're used by other programs).
The problem is that my program also needs to be able to add new rows to this table. I have a set of values I'm supposed to use for these extra columns when my program creates a new row (these values aren't database defaults but are specific for new rows coming from my program). I've been trying to use a EntityTypeConfiguration to map all the columns, but I can't find a way to set default creation values for unmapped columns.
Is there any way to make EF6 aware of these unmapped columns and set specific default values on INSERT (but not alter existing values on UPDATE)?
You have to map this columns in your model, you can't create default values if you don't map these properties. What you can do is set this properties as private in your model and the map with Entity framework as is described in this blog http://romiller.com/2013/01/23/ef6-code-first-mapping-all-private-properties-using-custom-conventions/ using reflection.

Is it possible to mix database first and code first models with entity framework?

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.

Oracle View base on a PIVOT query not null values

When creating a View based on a PIVOT query all the view fields become NULLABLE in the view metadata, is there any way to make them NOT NULLABLE?
I'm using the NVL function in the pivoted fields I need to be NOT NULL but they still become NULLABLE.
This is a problem to me because I'm using MS Entity Framework and it won't update the model based on tables or views without NOT NULLABLE columns.
#Miguel, I don't know the "MS Entity Framework" but the name makes it sound like a framework that is oriented towards editing data. 'Entity' is typically used for structuring a cache of database data in preparation for changing and updating that data back into the database. This does not seem like what you want to do.
Re-reading this question I believe that you have some sort of pivot generator you are using to create the view on-the-fly for the user. For this reason you do not intend to revise the Entity Model. I don't think you need an entity model at all.
An Entity Framework is likely to be looking for NOT NULL columns in order to find a 'primary key' or other row-level identifier that it can use. Why does it want these?
provide a key usable to update any row
provide key for paginating the result set
provide a key to support in-memory filtering of the result set
support dynamic sorting operations on the result set
I also surmise you have some sort of UI control that presents 'Entity' collections very nicely and so you want to use that control.
The control may not need an 'Entity' - check to see what its interface is. Perhaps there is a superclass of Entity or an interface that you can generate rather than an updateable Entity. If you can do that, you should be able to present it in the spiffy UI control and not hit the wall with your NULLABLE columns.
One of possible solutions is generating a new table on the fly based on results of query and tuning constraints for this table after that.
I don't like this method for too many dynamic SQL :)
Another solution is a prebuilt materialized view.
Look here (Oracle docs) for "ON PREBUILT TABLE Clause".
You need to update your model in Visual Studio (VS). Because this doesn't know what type information is in every column. Then you have to specify in the query of pivot table the data type. For example, Use to_number for specify a explicit conversion. When you going to update the model in VS you must based in for example materialized view (with explicitly defined data types). Please create Materialized view with explicitly defined data types based in the pivot table (this have to contain not only nvl function else defined data types, string, number, etc ) and then Update your model.
Only Materialized view? No, it can be a table (but is troublesome). Can be It direct of the pivot table? Does not always work (as in your case). Important Is to have defined data types.
You could use code-first if you don't have to many of these views, Scott Gu has a good article "Code first with existing database" that shows how to do this.
This might entail having 2 ways to access the db, which may or may not work for you.

Retrieving SQL View with Entity

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.

Entity Framework Design - Multiple "Views" for the data

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.

Categories