EzDevInfo.com

ef-code-first interview questions

Top ef-code-first frequently asked interview questions

Ignoring a class property in Entity Framework 4.1 Code First

My understanding is that the [NotMapped] attribute is not available until EF 5 which is currently in CTP so we cannot use it in production.

How can I mark properties in EF 4.1 to be ignored?

UPDATE: I noticed something else strange. I got the [NotMapped] attribute to work but for some reason, EF 4.1 still creates a column named Disposed in the database even though the public bool Disposed { get; private set; } is marked with [NotMapped]. The class implements IDisposeable of course but I don't see how that should matter. Any thoughts?


Source: (StackOverflow)

Decimal precision and scale in EF Code First

I'm experimenting with this code-first approach, but I'm find out now that a property of type System.Decimal gets mapped to a sql column of type decimal(18, 0).

How do I set the precision of the database column?


Source: (StackOverflow)

Advertisements

Entity Framework: One Database, Multiple DbContexts. Is this a bad idea?

My impression to date has been that a DbContext is meant to represent your database, and thus, if your application uses one database, you'd want only one DbContext. However, some colleagues want to break functional areas out into separate DbContext classes. I believe this comes from a good place -- a desire to keep the code cleaner -- but it seems volatile. My gut's telling me it's a bad idea, but unfortunately my gut feeling is not a sufficient condition for a design decision.

So I'm looking for A) concrete examples of why this might be a bad idea, or B) assurances that this'll all work out just fine.


Source: (StackOverflow)

Database in use error with Entity Framework 4 Code First

I have an MVC3 and EF 4 Code First application, which is configured to change the DB when the model changes, by setting the DB Initializer to a DropCreateDatabaseIfModelChanges<TocratesDb>, where TocratesDb is my derived DbContext.

I have now made a change to the model, by adding properties to a class, but when EF tries to drop and recreate the DB, I get the following error:

Cannot drop database "Tocrates" because it is currently in use.

I have absolutely no other connections anywhere open on this database. I assume that my cDbContext still has an open connection to the database, but what can I do about this?

NEW: Now my problem is how to re-create the database based on the model. By using the more general IDatabaseInitializer, I lose that and have to implement it myself.


Source: (StackOverflow)

How to store images using Entity Framework Code First CTP 5?

I'm just trying to figure out if there is a simple way to store and retrieve binary (file) data using EF Code First CTP 5? I would really like it to use the FILESTREAM type, but I'm really just looking for some way to make it work.


Source: (StackOverflow)

Entity Framework Code-first default data in database

How do I handle situations in which I need pre-existing data before the app is started or right after the database is generated. For example, I have a list of countries in which I'd like to load into the database after code-first generates it. How do I do this?

App is structured as follows:

Repository > Service > WebMVC

The xml is in the WebMVC project.


Source: (StackOverflow)

Debug code-first Entity Framework migration codes

I'm using Entity Framework code first in my website and I'm just wondering if there is any way to debug the migration codes. You know, like setting breakpoints and stuff like this.

I'm using Package Manager Console to update the database using update-database.

Thanks


Source: (StackOverflow)

Entity Framework Stored Procedure Table Value Parameter

I'm trying to call a stored procedure that accepts a table value parameter. I know that this isn't directly supported in Entity Framework yet but from what I understand you can do it using the ExecuteStoreQuery command off of the ObjectContext. I have a generic entity framework repository where I have the following ExecuteStoredProcecdure method:

public IEnumerable<T> ExecuteStoredProcedure<T>(string procedureName, params object[] parameters)
{
    StringBuilder command = new StringBuilder();
    command.Append("EXEC ");
    command.Append(procedureName);
    command.Append(" ");

    // Add a placeholder for each parameter passed in
    for (int i = 0; i < parameters.Length; i++)
    {
        if (i > 0)
            command.Append(",");

        command.Append("{" + i + "}");
    }

    return this.context.ExecuteStoreQuery<T>(command.ToString(), parameters);
}

The command string ends up like this:

EXEC someStoredProcedureName {0},{1},{2},{3},{4},{5},{6},{7}

I tried to run this method on a stored procedure that accepts a table valued parameter and it breaks. I read here that the parameters needed to be of type SqlParameter and the table valued parameter needs to have the SqlDbType set to Structured. So I did this and I get an error stating:

The table type parameter p6 must have a valid type name

So, I set the SqlParameter.TypeName to the name of the user defined type I created on the database and then when I run the query I get the following truly helpful error:

Incorrect syntax near '0'.

I can get the query to run if I revert back to ADO.NET and and execute a data reader but I was hoping to get it to work using the data context.

Is there a way to pass a table value parameter using ExecuteStoreQuery? Also, I am actually using Entity Framework Code First and casting the DbContext to an ObjectContext to get the ExecuteStoreQuery method available. Is this necessary or can I do this against the DbConext as well?


Source: (StackOverflow)

Entity Framework code first many-to-many mapping table

From examples that I have seen online and in a Programming Entity Framework CodeFirst book, when you have a collection on both classes EF would create a mapping table such as MembersRecipes and the primary key from each class would link to this table.

However when I do the below, I instead get a new field in the Recipes table called Member_Id and a Recipe_Id in the Members table.

Which only creates two one-to-many relationships, but not a many-to-many so I could have Member 3 linked to Recipes (4,5,6) and Recipe 4 linked to Members (1,2,3) etc.

Is there a way to create this mapping table? and if so how do you name it something else such as "cookbooks" ?

Thanks

    public abstract class Entity {
        [Required]
        public int Id { get; set; }
    }   

    public class Member : Entity {
        [Required]
        public string Name { get; set; }

        public virtual IList<Recipe> Recipes { get; set; }
    }

    public class Recipe : Entity {  
        [Required]
        public string Name { get; set; }

        [ForeignKey("Author")]
        public int AuthorId { get; set; }
        public virtual Member Author { get; set; }

            ....

        public virtual IList<Member> Members { get; set; }
    }

UPDATE: Below is another approach I have tried which doesn't use the Fluent API and replaces the AuthorId & Author on Recipe with an owner flag, I have also renamed the below example from Cookbooks to MembersRecipes, this also fixes my issue similar to the answer but as mentioned has further implications.

public class MembersRecipes {

    [Key, Column(Order = 0)]
    [ForeignKey("Recipe")]
    public int RecipeId { get; set; }
    public virtual Recipe Recipe { get; set; }

    [Key, Column(Order = 1)]
    [ForeignKey("Member")]
    public int MemberId { get; set; }
    public virtual Member Member { get; set; }

    public bool Owner { get; set; }
}

and in Recipe & Member classes I changed the collections to

public virtual IList<MembersRecipes> MembersRecipes { get; set; }

Source: (StackOverflow)

One DbContext per request in ASP.NET MVC (without IOC container)

Apologies if this has already been answered, but how do you guarantee one Entity Framework DbContext per request if you are not using an IOC container? (The answers I've come across so far deal with IOC container solutions.)

It seems like most solutions hook into the HttpContext.Current.Items dictionary, but how do you guarantee disposal of the DbContext when the request is finished? (Or is disposal not absolutely necessary with an EF DbContext?)

Edit

I'm currently instantiating and disposing my DbContext in my controllers, but I also have several separate instantiations of my DbContext in ActionFilters and my MembershipProvider (and I just noticed, also a couple validators). So, I thought it might be a good idea to centralize instantiation and storage of my DbContext to reduce overhead.


Source: (StackOverflow)

EF: Validation failing on update when using lazy-loaded, required properties

Given this extremely simple model:

public class MyContext : BaseContext
{
    public DbSet<Foo> Foos { get; set; }
    public DbSet<Bar> Bars { get; set; }
}

public class Foo
{
    public int Id { get; set; }
    public int Data { get; set; }
    [Required]
    public virtual Bar Bar { get; set; }
}

public class Bar
{
    public int Id { get; set; }
}

The following program fails:

object id;
using (var context = new MyContext())
{
    var foo = new Foo { Bar = new Bar() };
    context.Foos.Add(foo);
    context.SaveChanges();
    id = foo.Id;
}
using (var context = new MyContext())
{
    var foo = context.Foos.Find(id);
    foo.Data = 2;
    context.SaveChanges(); //Crash here
}

With a DbEntityValidationException. The message found in EntityValidationErrors is The Bar field is required..

However, if I force loading of the Bar property by adding the following line before SaveChanges:

var bar = foo.Bar;

Everything works fine. This also works if I remove the [Required] attribute.

Is this really the expected behavior? Are there any workarounds (besides loading every single required reference every time I want to update an entity)


Source: (StackOverflow)

CodeFirst EF4.1 MVC Against legacy database - Multiplicity conflicts

No matter which way I mix it, it gives me errors. I have a feeling I'm missing something obvious as I keep getting these errors.

One or more validation errors were detected during model generation:

System.Data.Edm.EdmAssociationType: : Multiplicity conflicts with the referential constraint in Role 'Venue_Courses_Source' in relationship 'Venue_Courses'. Because all of the properties in the Dependent Role are non-nullable, multiplicity of the Principal Role must be '1'.

System.Data.Edm.EdmAssociationEnd: : Multiplicity is not valid in Role 'Venue_Courses_Target' in relationship 'Venue_Courses'. Because the Dependent Role refers to the key properties, the upper bound of the multiplicity of the Dependent Role must be 1.

A Course can only have one venue, venues can be used by many Courses

public class Course
{
    [Key]
    public virtual int Id { get; set; }
    public string Title { get; set; }
    public DateTime StartDate { get; set; }
    public int VenueId { get; set; }

    public virtual Venue Venue { get; set; }
}

public class Venue
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Course> Courses { get; set; }
}


protected override void OnModelCreating(DbModelBuilder modelBuilder)
{

    #region Courses
    //Table Alias
    modelBuilder.Entity<Course>().ToTable("DBSCHEMA.TR_COURSES");
    //Keys
    modelBuilder.Entity<Course>().HasKey(c => c.Id);
    //Joins
    //Join to Venues
    modelBuilder.Entity<Course>().HasOptional(c => c.Venue);

    //Fields
    modelBuilder.Entity<Course>().Property(c => c.Id).HasColumnName("COURSE_ID");
    modelBuilder.Entity<Course>().Property(c => c.Title).HasColumnName("CR_TITLE");
    modelBuilder.Entity<Course>().Property(c => c.StartDate).HasColumnName("START_DATE");
    modelBuilder.Entity<Course>().Property(c => c.VenueId).HasColumnName("VENUE_ID");
    #endregion


    #region Venues
    //Table Alias
    modelBuilder.Entity<Venue>().ToTable("DBSCHEMA.VENUES");
    //Keys
    modelBuilder.Entity<Venue>().HasKey(v => v.Id);
    //Joins
    modelBuilder.Entity<Venue>().HasMany(venue => venue.Courses);
    //Fields
    modelBuilder.Entity<Venue>().Property(v => v.Id).HasColumnName("VENUE_ID");
    modelBuilder.Entity<Venue>().Property(v => v.Name).HasColumnName("VENUE_NAME");
    #endregion

}

Source: (StackOverflow)

Using Entity Framework (code first) migrations in production

I'm just looking into using EF migrations for our project, and in particular for performing schema changes in production between releases.

I have seen mentioned that there is an API to perform these migrations at run-time using the DbMigration class, but I can't find any specific examples.

Ideally, I would want one DbMigration file for every database change, and for those changes to be applied automatically on application start up from the current version up to the latest version.


Source: (StackOverflow)

Unique key with EF code first

I have a following model in my project

public class Category
{   
    public Guid ID { get; set; }
    [Required(ErrorMessage = "Title cannot be empty")]
    public string Title { get; set; }
}

and I'm trying to make Title as unique key, I googled for the solution, but couldn't find any. Can any suggest me how to do it, please?


Source: (StackOverflow)

Entity Framework 6 Code first Default value

is there "elegant" way to give specific property a default value ?

Maybe by DataAnnotations, something like :

[DefaultValue("true")]
public bool Active { get; set; }

Thank you.


Source: (StackOverflow)