EntityFramework code-first ignoring derived columns when creating database - database

I would like some of tables in my database to have standard columns such as createdBy, ModifiedBy, CreatedDateTime, modifiedDateTime etc.
So, I created an interface with those properties and implemented the interface in an abstract base class. I derived my concrete classes from this base class.
This is a brand new application using Code-First approach. When I create the database, the derived properties are ignored. The tables are created with just the properties in the derived classes.
I'm not sure why.
Thank you.

I'm not sure exactly what was different, but tried it again with the following changes and it worked:
gave dbCreator rights in the database for the user
Changed the properties in my base class to be in the format (similar change for the other properties):
public string CreatedBy { get; set;}

Related

Entity Framework data reader incompatible with column names with spaces (database first)

I'm trying to wrap Entity Framework (6.4.0) around a SQL View (SQL Server) where a couple of columns have spaces in the column names. For example, one column in SQL is "Badge ID", when I wrap EF around this view it renames the column "Badge_ID"
When I try to query, EF throws exception that the data reader is incompatible (makes sense):
System.Data.Entity.Core.EntityCommandExecutionException: The data
reader is incompatible with the specified 'Model.vwEmpOrg'. A member
of the type, 'Badge_ID' does not have a corresponding column in the
data reader with the same name.'
I tried a solution from a code-first approach where in the class definition you can annotate the column name like so:
namespace EXAMPLE.Models
{
using System.ComponentModel.DataAnnotations.Schema;
public partial class vwEmpOrg
{
[Column("Badge ID")]
public string Badge_ID { get; set; }
However the same is exception is still thrown. What am I missing? Why doesn't the annotation on the column name work?
You will need to post more code specific to your Entity, especially anything that has been auto-generated, and the underlying View because EF6 + SQL Server have no issues with Spaces in column names using DB First.
AFAIK you cannot leverage Code-First with SQL Views. Code First would expect to create a Table called vwEmpOrg. You can certainly map an EF Entity to an existing view using annotations or explicit entity configurations.
For example I have a Table called Persons with PersonId & Name, I create a View called vwPersons with:
SELECT PersonId AS [Person ID], Name
FROM dbo.Persons
Then for an entity:
[Table("vwPersons")]
public class ViewPersons
{
[Key, Column("Person ID")]
public int PersonId { get; set; }
public string Name { get; set; }
}
This works perfectly fine. For argument's sake to ensure that EF wasn't pulling any defaulting to conventions, I renamed the view's column alias to "Some ID", and renamed the key in the Entity to "Fudgesicle" pointed at "Some ID", and it was fine pulling that. (Nothing linking back to a "PersonId" in the underlying table)
I'd check that your code is actually using that entity definition for vwEmpOrg or the mapped BadgeId and not that the DbContext is actually using a generated model class in a different namespace. (If you had been using EDMX's or similar)

Can entity framework database-first successfully build models from any SQLServer db?

I'm considering using entity framework database-first approach. The database in question uses various non-standard techniques, eg 'informal' foreign keys. I'd like to confirm that it's still possible to create a usable EF model from this database, even if all the relationships are not recognised?
Yes, you can do this. Generate the model from the database as normal, then modify the generated entities in order to introduce the relationships. You'll need to set a Null database initializer to tell EF it should not try and update the database to match its model:
Database.SetInitializer(new NullDatabaseInitializer<MyContext>());
There's no requirement for foreign keys to exist in the database to match your model - as long as the navigation properties have been added on the entities, EF will generate the correct SQL queries accordingly.
I would recommend the use of the [ForeignKey] attribute to clarify the names of your foreign key fields for when they don't conform to EF's expected patterns (or you could modify the Conventions accordingly). For example...
public class Child {
// ...
public int Parent_ID { get; set; } // <-- non-standard name
// Add these to introduce the navigation property without a formal relationship
[ForeignKey("Parent_ID")]
public virtual Parent Parent { get; set; }
}
I have used this approach on a MySQL database with no foreign keys at all.

Insert error with dapper dot net Cannot update identity column

I'm new add dapper dot net so do forgive me if this question is quite easy for you.
I have my object wich I would like to save to te database. But when I execute my update command I get an error saying that I cannot update the identy column.
I'm not aloud to make any changes to the properties of my sql database, I'm using dapper extension and my project is written in vb.net.
How can I save my object?
A little old post but I was experiencing same problem. In my case I solved the problem creating a POCO class without the Identity column .
My entity is:
public class MyEntity
{
public decimal Id {get;set;} // Marked at SQL Db as Identity
other properties
}
To work with dapper-extensions Insert just remove Identity column at your POCO class
public class MyEntity
{
other properties
}
As you said you can't change the database, but at your code you could create your own poco's.

Entity framework foregin key in another database

So i like MVC and EF6 but I keep coming across fundamental problems with the way it / I work.
I have an app ( a very simple one) in there one of my tables references a field in another database, how would EF handle this , it seems to get very complicated whereas in the past it would have been a simple ADO.NET call to a stored procedure or something ( I am aware I can use SP's with EF, but really, what's the point , may as well just use ADO.NET again), example model below:
[Table("Target")]
public partial class Target
{
public int ID { get; set; }
public int SomeForeignKeyInMyDbID { get; set; }
public Guid? FOREGINKEYINANOTHERDB { get; set; }
}
when I scaffold views based of this it automatically creates the drop down menus etc really well but it (obviously) cannot pickup the reference to the foreign key in another field, as I want to store the ID of the foreign key in the database but get the value of it for drop downs etc, I store the ID instead of the value for reporting reasons.
I thought that I would just be able to get a context to my other db, grab the values I need and bind them to the drop down list but the model structure is so tightly defined that I face hurdle after hurdle on this.
I read somewhere that my best option may be to use SP's for CRUD operations and then perform a LINQ to EF query fro the index view and do a join on foreginkeyfromanotherdb field.
Any help much appreciated.
Thanks

Need advice on structure of my database, to create useful Entities

I need people's advice as to whether this the best way to achieve what I want. Apologies in advance if this is a little to subjective.
I want to use Entity Framework V.1 to create something similar to the following C# classes:
abstract class User
{
public int UserId;
public string TelephoneNumber;
}
class Teacher : User
{
public string FavorateNewspaper;
}
class Pupil : User
{
public string FavorateCartoon;
}
I need people's advice as to how to best to persist this information.
I plan to use SQL Server and the normal Membership Provider. It will create for me a table called aspnet_Users. There will be two roles: Teacher and Pupil.
I will add fields to the table aspnet_Users which are common to both roles. Then create tbl_Teachers and tbl_Pupils to hold information specific to one role.
So My database will look a bit like this:
aspnet_Users
int UserId
varchar TelephoneNumber
tbl_Teachers
int UserId
varchar FavorateNewspaper
tbl_Pupils
int UserId
varchar FavorateCartoon
The idea of course being that I can match up the data in aspnet_Users to that in either tbl_Teachers or tbl_Pupils by joining on UserId.
So to summarise, my questions are:
Is my database structure the best option to achieve these classes?
Should I try to wrap the Entities within my own POCO classes?
Should I change my database structure so that EF creates entities which are closer to the classes I want?
EDIT: I re-arranged my question it make it a bit clearer what I'm asking.
If you're using EF 1, then POCO can be a bit unpleasant. Unless there's a good reason not to, I'd just use normal EF entities. Your database model is fine, by the way, and is an example of TPT (Table Per Type) inheritance mapping. You could either use the wizard to create entites from the databaes, or create your entites and map them to the associated tables. If you do the former you'd initially end up with three unrelated entities. You'd then use the designer to tell EF that Pupil and Teacher inherit from User, and that User is abstract.
In general, one of the strengths of EF is that the entities don't have to match that closely to the tables that persist them. In this case though there's a natural mapping.

Resources