Entity Framework - change display name of tables/entities - c#

As the title suggests, I was wondering if it's possible to change the display name of my tables across all of my application.. currently my tables from my DB have complicated names and was wondering if I can change the display name so that it's more user-friendly.
Is there a class I can create that would do that for me?
I've looked at the following thread but not sure if this applies to my scenario.. I'm new to EF :)
Thanks!
Additional Info:
I'm using the database first approach and currently have an EDMX setup.

If you are using the Code-first approach, you should check the answer from Vitor M. Barbosa. If you are using Database First (has an EDMX), you can achieve that by changing the Name of the table/entity in your diagram. Internal EF will map that name to the table in the database.

If you're doing code-first, you'll just need some data annotations, e.g.:
[Table("TableName")]
public class Table
[Column("BlogDescription", TypeName="ntext")]
public String Description {get;set;}

Related

Cannot generate C# class from PostgreSQL view using Npgsql + EF6 code first

I am trying to use entity framework code first method to connect to PostgreSQL database, and when I use entity data model wizard in visual studio to generate C# class from database, it can generate classes for each table in database successfully, but the views in database cannot be generated.
(source: linearbench.com)
(source: linearbench.com)
Can someone told me where I did wrong? I use Entity framework 6.1.3, with Npgsql 2.2.5. PosgreSQL database is version 9.3.6 installed on a Ubuntu server.
Thanks
I know this question is a little bit old now, but ill chime in here for anyone else who may be looking for solutions here. My answer may not be exactly what the question was looking for, however, it has sufficed as a work around solution for me.
The problem with views is that entity framework has a hard time determining the primary key column for them. In Sql Server, you can use ISNULL() function to trick EF into thinking that the column is a key column, but the equvilant coalesce() function in postgres isn't good enough for EF. I also tried generating auto-incrementing row id column, joining to other tables with primary keys, etc; no luck with any of these.
However, something that has just about emulated the functionality that I needed as far as being able to query my views into my view objects is to just extend your context class with functions that call Database.SqlQuery and return it as a Queryable
For example:
Suppose a view in your database, "foo", with columns id, bar, baz. You can write your own POCO to hold the view data like so
public class foo
{
public int id { get; set; }
public string bar { get; set; }
public string baz { get; set; }
}
and then extend your context class with a partial class definition like this
public partial class FooContext : DbContext
{
public IQueryable<foo> foo =>
this.Database.SqlQuery<foo>( "select * from foo" ).AsQueryable();
}
And then you can query it from your context just the same as any other table
context.foo.where( x => id > 100 ).toList(); //etc,etc
You wont be able to do inserts or use any of those extra capabilities that usually come with the standard DbSet, but Views are typically used as read-only queries anyways (unless youre using some special insert triggers)...
But this gives you a base call that will query the entire view, and it doesn't hit the database because its left as a queryable, so you're free to call any other LINQ extensions on it such as Where to filter it to the results you want.
I migrated from sql server to postgres sql using npgsql lib, and this fix allowed my views to work without having to make any changes to my programs codebase, just as if nothing had changed at all, and despite the fact that the edmx would not generate my view objects due to lack of a (discernible) primary key.
Hope this helps!

Name does not exist in the current context but table is listed

I have a problem with Linq, I have a table called FavoriteMessage but whenever I try to query this I get the error,
The name does not exist in the current context
I can see the table listed so I am not sure what is going on, here is a screenshot
public class WforceContext : IdentityDbContext<ApplicationUser>{}
You need to add DbSet here if it's not done by other means. For your example:
public DbSet<FavoriteMessage> FavoriteMessages{ get; set; }
FavoriteMessage is the MODEL of your table and FavoriteMessages is the name of it in your context.
If you lack the model, you 1st need to make model, there is plenty of info on how to do that since it's really essential to learn how to do so :)
just drag and drop this table in your dbml file again and build the project.
In my case the problem was with Automapper, i forgot that i was ignoring a field on the type mapping and it was not available on the subsequent query.
I just had to include it on the data context.

Changing the Nhibernate entity to point to new table

I am using FLH and recently I changed the name of the table. I dont want to propagate the changes all the way across my layers. Is there a way, where I can retain the same entity name and just change the mapping. For example, my current entity name is Issuer and the table name is also issuer. However, the table name is changed to "counterparty" and I want to retain the entity name as Issuer. How can I achieve this?
I found the answer for the above problem. I made use of IAutomappingOverride interface.
The sample code is below
public class IssuerMap : IAutoMappingOverride<Issuer>
{
public void Override(AutoMapping<Issuer> mapping)
{
mapping.Table("Counterparty");
}
}
Also found some related links
Fluent Nhibernate - How to specify table name
You would need to have a Table("Counterparty") clause in your classmap, as in How to specify table name in Fluent NHibernate ClassMap class?

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.

Entity Framework: subset entity of larger entity

Sooo basically I have a table called Comment. On that table I have three fields,
ID
Title
Text
I've created an Entity object for the table already and it maps all three fields, but what I want now is another Entity called CommentHeader that will map only ID and Title. I want to only load the titles of all the comments and not the text for speed reasons. So what's the best way for going about this?
I'm not looking for a Select statement with a var object. I can figure that one out on my own and I really don't like that solution because I'd much rather abstract it behind an Entity object.
I've tried the obvious solution, which was to just copy the original Entity object and delete Text from it. That resulted in an error because only one Entity can map to one table without conditions. It sounds to me like I have no choice but to use a Select statement. I just wanted to make sure before I did something stupid.
(By the way this example only has three fields for simplicity's sake. Assume that the header could have considerably more fields in it. This is the primary reason I don't want to just use a select with a var object, because it's not just one field but could be a whole bunch of fields).
The easiest way probably would be to create a view ("CommentHeaders") in the database that only selects ID and title from the Comment table. Then update your model and add the view, which will create a new entity based on those columns.

Categories