add my own property to EF designer - entity-framework

I using vs2010 and the built-in EF designer against SQL server Compact 4.0 local database that in my project. ( design-first)
I tried to add (through the designer) to one of the entities a new property that doesn't exist in the DB (nor planed to) by: add-new scalar property.... , but when i was tring to validate it, i got an error:
property "x" is not map
my question:
can i add my own properties to the schema through the designer. and that properties won't be exist in the underline DB.(I thought i could)?
if I can, how?

You can add non db fields to your entity by creating a partial class of that entity with the required properties. These won't be used for the ORM.
public partial class MyEntity {
public string StringStatusCode { get;set;}
}

Related

AutoMapping stored procedure results

I'm wondering if there is any way to map a stored procedure result into into a class.
This is what I have:
// DbContext Class:
public DbSet<StoredProcedureModelResult> SPMR { get; set; }
// Service Class:
var result = ctx.Set<StoredProcedureModelResult>().FromSql("getXXXX p1 = {0},1).ToList();
This works well, however, I'm using database migrations and every time I add one this thing creates StoredProcedureModelResult as a table...
I tried to ignore it onModelCreating:
modelBuilder.Ignore<SPModels.test>();
but this throws an exception:
Cannot create a DbSet for 'StoredProcedureModelResult ' because this type is not included in the model for the context
I just want use the benefit of mapping, and not to get a table creation, this is a simple model (non-entityType)
BTW
.NET Core 1.1
Web API
EF Core (code-first)
Thank you
You don't need to make the type an Entity type (by registering a DbSet in your DbContext). Just have a method that returns IEnumerable<StoredProcResults> (can be in your DbContext), and in it run
dbContext.Database.SqlQuery<StoredProcResults>(...)
See Database.SqlQuery<T>(...)

How to add Foreign Key Properties subsequently to a Code First Model?

Given the Model:
Public Class Customer
Property Id() As Guid
Property FirstName() As String
Property MiddleName() As String
Property LastName() As String
Property Addresses() As ICollection(Of Address)
End Class
Public Class Address
Property Id() As Guid
Property Name() As String
Property Street() As String
Property City() As String
Property Zip() As String
Public Property Customer() As Customer
End Class
Entity Framework 6 Code First has created a column called Customer_Id in my table Addresses. Now, I'd like to add a Property Customer_Id to my class Address that represents the existing foreign key relation:
Public Class Address
Property Id() As Guid
Property Name() As String
Property Street() As String
Property City() As String
Property Zip() As String
Public Property Customer() As Customer
//Added
Public Property Customer_Id() As Guid
End Class
Unfortunately this results in an InvalidOperationException while creating the DbContext saying:
The model backing the 'DataContext' context has changed since the database was created.
I tried different property names (with and without underscore, different casing). But still no luck. So, what is the correct way to add those properties subsequently without the need for migrations? I assume it's possible, because the model does not really change, I am only changing from an implicit declaration of a property to an explicit...
Update:
The responses show me, that I did not explain the problem very well. After some more reading I found the correct names now: I have an application which is installed several times at customer locations (therefore dropping and recreating the database is no option). Currently, it depends on Entity Framework's Independent Associations, but I want to have the Foreign Key in my entity as well (this is no change to the model, the foreign key is already there, but does not exist as a property in my entity, since this is currently only relying on the IA instead). I did not manage to add it without EF thinking my Database is outdated.
for me two ways :
drop table __MigrationHistory : that is have the new model runs, but forget migration functionalities
create a new db by changing the connection string of the application. Replace old __MigrationHistory by __MigrationHistory of the newly created db
Never tested the second solution, but it should work.
Before using any solution:
backup you db.
Before using first solution: are you sure you will never need migration functionalities ?
This exception is because you change your model. You have to set migration strategy. Please look at:
http://msdn.microsoft.com/en-us/data/jj591621#enabling
(edited)
First of all you have to remove that exception. Even if you didn't add any new column to your database your model has changed because you added new property to Address class. If you check your DB you will find dbo.__MigrationHistory table with Model column. Last (earliest) value from that column is used for checking that your model and DB are compatible. I'm not sure but I think that EF stores there binary serialized model. So the solution is - recreate DB or add migration (probably empty migration).
(edited)
When you want to set FK you can do this very simple by Data Annotations
// c# example
public class Address
{
...
public string CustomerId { get; set; }
[ForeignKey("CustomerId")]
public Customer Customer { get; set; }
}
or in fluent api
// c# example
modelBuilder.Entity<Address>()
.HasRequired(arg => arg.Customer)
.WithMany()
.HasForeignKey(arg => arg.CustomerId);
or look at:
http://weblogs.asp.net/manavi/archive/2011/05/01/associations-in-ef-4-1-code-first-part-5-one-to-one-foreign-key-associations.aspx
http://msdn.microsoft.com/en-us/data/hh134698.aspx

Entitfy Framework DbContext and xxxEntities?

I have a SQL server db ( with tables etc) and ive installed ef6 in order to use async stuff ( p.s. im new to ef).
So I added this :
played with the wizard and created a valid edmx files.
My db name is DUMP so it added Dumpentities suffix :'
so now i can do :
de = new DumpEntities1();
var data=de.AgeGroups.ToList()
But why don't I Have DbContext ? like I see in many places ?
Is xxxEntityes is a replacement for DbContext ?
cause it seems i can do all actions with xxEntites ...
edit
Ive searched "dbcontext" in my solution and apprently i do have it :
So what is going on here?
does using xxxEntiyies is the new way ?( and not doing xxxContext = new xxxContext()...even if I wanted - I dont have it...)
You should not use DbContext directly (that will not make sense) in Entity Framework. Instead you use your own custom context - class inherited from DbContext which holds sets specific to your application. When you use database first approach this custom entity class will be generated based on edmx file data, which in his turn will be generated based on database schema.
Regarding to naming... its not obvious but custom context which will be generated, will have same name as connection string name when you are creating edmx file:
Actually this will be default name for Entity Container of your conceptual entity model. If you will open edmx file in designer and take a look on its properties, you will see:
If you will change this name, context will be re-generated with name you have provided.

Entity Framework 4.1 DbContext Extending Partial Classes

Building a C# application using EF 4.1 with Database First. My question centers around using extension methods to return values through the DbContext object.
My entities were created as partial classes by the DbContext generator. I have a Projects table and a related Managers table and through the context object I can perform LINQ queries and access projects and the assigned project manager. If the Manager table has firstname and lastname fields how would I write my extension as a property or method to concatenate the first and last name fields so that when I query for a project and use the manager relation the property FullName returns the combined value?
This example has a variable _projects populated with a list of Projects created using LINQ query:
Fields["manager"].Value = _projects[i].Project.ProjectManager.FullName
I can makethe FullName property into a method and pass the id for the manager however wouldn't that make it into an additional query? Thanks for the help.
If you know that you're always going to be accessing the ProjectManager navigation property, you can include it in the initial query by using the Include method
var projects = (from p in ctx.Projects
select p)
.Include(p => p.ProjectManager)
.ToList();
Then you can add the following property to your Manager class (in a seperate file than the generated one)
public string FullName
{
get { return FirstName + " " + LastName; }
}
And access it using
var manager = projects[0].ProjectManager.FullName;
If I missinterpreted your question, could you provide an example of what your code would look like using your proposed extension method?

Entity framework: Database first/Code first hybrid

I am trying to create a custom Entity Framework (4.2) entity that would be mapped to my database like it would be done in a Code first approach.
The issue is that my entity framework data model is using Database first.
How can I add my custom entity to entity framework's context?
If by the Database first you mean that you already have EDMX created from exiting database you simply cannot use code first. You must create table and update model (EDMX) from the database to include it in EDMX.
Edit based on comment:
I want to create a BriefUser entity that would basically be a lighter
version of User but it would have properties retrieved from User's
foreign keys.
Well this is possible. You can either create BriefUser as common class and use projection in query.
var breifUser = (from x in context.Users
where ...
select new BriefUser
{
// Fill BreifUser's properties here
}).FirstOrDefault();
You can even refactor former code to reusable extension method:
public static IQueryable<BriefUser> ProjectUser(this IQueryable<User> query)
{
return query.Select(x => new BreifUser()
{ // Fill BreifUser's properties here });
}
and use it like:
var briefUser = context.Users.ProjectUser().FirstOrDefault(...);
It is also possible to define your new class as "entity view". The first problem is that each table can be mapped to only one entity (except some advanced concepts like inheritance or splitting) so you cannot define your BriefUser as a new entity type because mapping both User and BriefUser to UserTbl would violate this rule. You must use special construct called QueryView.
QueryView is view in mapping level. It allows you to create new mapped type which is projection of existing mapped entities defined directly in EDMX's MSL part. The projection is defined as custom Entity SQL query. The problem is that QueryView has limitations:
It doesn't offer all Entity SQL features - for example it doesn't support aggregations (which I consider as really missing feature). Without aggregations you for example cannot create a new type which will contain property counting some related entities.
It is not supported in designer. You must edit your EDMX as XML to define QueryView and you must write Entity SQL query yourselves.
Resulting type is a "view" and it is read-only.
I want to keep the EDMX file, but also be able to add an entity
(BriefUser) to EF's context.
This is not possible. Your BreifUser is only projection / view and EF is not able to track changes back to originating tables so you cannot add BreifUser to context and persist it. In case of QueryView you can achieve it if you define custom stored procedures which will no how to decompose BreifUser and modify all related tables. These stored procedures must be imported to the EDMX and mapped to data modification operations of the view entity. Btw. same will happen if you map your entity to the database view because EF takes all views as read-only.