EzDevInfo.com

entity-framework-4 interview questions

Top entity-framework-4 frequently asked interview questions

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details

I am having this error when seeding my database with code first approach.

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

To be honest I don't know how to check the content of the validation errors, Visual Studio shows me that its an array with 8 objects. so 8 validation Errors.

This was working with my previous model, but I made a few changes that I explain below:

  • I had an enum called Status, I changed it to a class called Status
  • I changed the class ApplicantsPositionHistory to have 2 foreign key to the same table

Excuse me for the long code, but I have to paste it all. The exception is thrown in the last line of the following code.

namespace Data.Model
{  
    public class Position
    {
        [DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.Identity)]   
        public int PositionID { get; set; }

        [Required(ErrorMessage = "Position name is required.")]
        [StringLength(20, MinimumLength = 3, ErrorMessage = "Name should not be longer than 20 characters.")]
        [Display(Name = "Position name")]              
        public string name { get; set; }

        [Required(ErrorMessage = "Number of years is required")] 
        [Display(Name = "Number of years")]        
        public int yearsExperienceRequired { get; set; }

        public virtual ICollection<ApplicantPosition> applicantPosition { get; set; }
    }

    public class Applicant
    {
        [DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.Identity)]      
        public int ApplicantID { get; set; }

        [Required(ErrorMessage = "Name is required")] 
        [StringLength(20, MinimumLength = 3, ErrorMessage="Name should not be longer than 20 characters.")]
        [Display(Name = "First and LastName")]
        public string name { get; set; }

        [Required(ErrorMessage = "Telephone number is required")] 
        [StringLength(10, MinimumLength = 3, ErrorMessage = "Telephone should not be longer than 20 characters.")]
        [Display(Name = "Telephone Number")]
        public string telephone { get; set; }

        [Required(ErrorMessage = "Skype username is required")] 
        [StringLength(10, MinimumLength = 3, ErrorMessage = "Skype user should not be longer than 20 characters.")]
        [Display(Name = "Skype Username")]
        public string skypeuser { get; set; }

        public byte[] photo { get; set; }

        public virtual ICollection<ApplicantPosition> applicantPosition { get; set; }
    }

    public class ApplicantPosition
    {
        [Key]
        [Column("ApplicantID", Order = 0)]
        public int ApplicantID { get; set; }

        [Key]
        [Column("PositionID", Order = 1)]
        public int PositionID { get; set; }

        public virtual Position Position { get; set; }

        public virtual Applicant Applicant { get; set; }

        [Required(ErrorMessage = "Applied date is required")] 
        [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
        [Display(Name = "Date applied")]     
        public DateTime appliedDate { get; set; }

        [Column("StatusID", Order = 0)]
        public int StatusID { get; set; }

        public Status CurrentStatus { get; set; }

        //[NotMapped]
        //public int numberOfApplicantsApplied
        //{
        //    get
        //    {
        //        int query =
        //             (from ap in Position
        //              where ap.Status == (int)Status.Applied
        //              select ap
        //                  ).Count();
        //        return query;
        //    }
        //}
    }

    public class Address
    {
        [StringLength(20, MinimumLength = 3, ErrorMessage = "Country should not be longer than 20 characters.")]
        public string Country { get; set; }

        [StringLength(20, MinimumLength = 3, ErrorMessage = "City  should not be longer than 20 characters.")]
        public string City { get; set; }

        [StringLength(50, MinimumLength = 3, ErrorMessage = "Address  should not be longer than 50 characters.")]
        [Display(Name = "Address Line 1")]     
        public string AddressLine1 { get; set; }

        [Display(Name = "Address Line 2")]
        public string AddressLine2 { get; set; }   
    }

    public class ApplicationPositionHistory
    {
        [DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.Identity)]
        public int ApplicationPositionHistoryID { get; set; }

        public ApplicantPosition applicantPosition { get; set; }

        [Column("oldStatusID")]
        public int oldStatusID { get; set; }

        [Column("newStatusID")]
        public int newStatusID { get; set; }

        public Status oldStatus { get; set; }

        public Status newStatus { get; set; }

        [StringLength(500, MinimumLength = 3, ErrorMessage = "Comments  should not be longer than 500 characters.")]
        [Display(Name = "Comments")]
        public string comments { get; set; }

        [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
        [Display(Name = "Date")]     
        public DateTime dateModified { get; set; }
    }

    public class Status
    {
        [DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.Identity)]
        public int StatusID { get; set; }

        [StringLength(20, MinimumLength = 3, ErrorMessage = "Status  should not be longer than 20 characters.")]
        [Display(Name = "Status")]
        public string status { get; set; }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using System.IO;

namespace Data.Model
{
    public class HRContextInitializer : DropCreateDatabaseAlways<HRContext>
    {
        protected override void Seed(HRContext context)
        {
            #region Status
            Status applied = new Status() { status = "Applied" };
            Status reviewedByHR = new Status() { status = "Reviewed By HR" };
            Status approvedByHR = new Status() { status = "Approved by HR" };
            Status rejectedByHR = new Status() { status = "Rejected by HR" };
            Status assignedToTechnicalDepartment = new Status() { status = "Assigned to Technical Department" };
            Status approvedByTechnicalDepartment = new Status() { status = "Approved by Technical Department" };
            Status rejectedByTechnicalDepartment = new Status() { status = "Rejected by Technical Department" };

            Status assignedToGeneralManager = new Status() { status = "Assigned to General Manager" };
            Status approvedByGeneralManager = new Status() { status = "Approved by General Manager" };
            Status rejectedByGeneralManager = new Status() { status = "Rejected by General Manager" };

            context.Status.Add(applied);
            context.Status.Add(reviewedByHR);
            context.Status.Add(approvedByHR);
            context.Status.Add(rejectedByHR);
            context.Status.Add(assignedToTechnicalDepartment);
            context.Status.Add(approvedByTechnicalDepartment);
            context.Status.Add(rejectedByTechnicalDepartment);
            context.Status.Add(assignedToGeneralManager);
            context.Status.Add(approvedByGeneralManager);
            context.Status.Add(rejectedByGeneralManager); 
            #endregion    

            #region Position
            Position netdeveloper = new Position() { name = ".net developer", yearsExperienceRequired = 5 };
            Position javadeveloper = new Position() { name = "java developer", yearsExperienceRequired = 5 };
            context.Positions.Add(netdeveloper);
            context.Positions.Add(javadeveloper); 
            #endregion

            #region Applicants
            Applicant luis = new Applicant()
            {
                name = "Luis",
                skypeuser = "le.valencia",
                telephone = "0491732825",
                photo = File.ReadAllBytes(@"C:\Users\LUIS.SIMBIOS\Documents\Visual Studio 2010\Projects\SlnHR\HRRazorForms\Content\pictures\1.jpg")
            };

            Applicant john = new Applicant()
            {
                name = "John",
                skypeuser = "jo.valencia",
                telephone = "3435343543",
                photo = File.ReadAllBytes(@"C:\Users\LUIS.SIMBIOS\Documents\Visual Studio 2010\Projects\SlnHR\HRRazorForms\Content\pictures\2.jpg")
            };

            context.Applicants.Add(luis);
            context.Applicants.Add(john); 
            #endregion

            #region ApplicantsPositions
            ApplicantPosition appicantposition = new ApplicantPosition()
            {
                Applicant = luis,
                Position = netdeveloper,
                appliedDate = DateTime.Today,
                StatusID = 1
            };

            ApplicantPosition appicantposition2 = new ApplicantPosition()
            {
                Applicant = john,
                Position = javadeveloper,
                appliedDate = DateTime.Today,
                StatusID = 1
            };        

            context.ApplicantsPositions.Add(appicantposition);            
            context.ApplicantsPositions.Add(appicantposition2); 
            #endregion

            context.SaveChanges(); --->> Error here
        }
    }
}

Source: (StackOverflow)

There is already an open DataReader associated with this Command which must be closed first

I have this query and I get the error in this function:

var accounts =
    from account in context.Accounts
    from guranteer in account.Gurantors

 select new AccountsReport
    {
        CreditRegistryId = account.CreditRegistryId,
        AccountNumber = account.AccountNo,
        DateOpened = account.DateOpened,
    };

 return accounts.AsEnumerable()
                   .Select((account, index) => new AccountsReport()
                           {
                               RecordNumber = FormattedRowNumber(account, index + 1),
                               CreditRegistryId = account.CreditRegistryId,
                                  DateLastUpdated = DateLastUpdated(account.CreditRegistryId, account.AccountNumber),
                               AccountNumber = FormattedAccountNumber(account.AccountType, account.AccountNumber)}).OrderBy(c=>c.FormattedRecordNumber).ThenByDescending(c => c.StateChangeDate);


 public DateTime DateLastUpdated(long creditorRegistryId, string accountNo)
        {
            var dateReported = (from h in context.AccountHistory
                                where h.CreditorRegistryId == creditorRegistryId && h.AccountNo == accountNo
                                select h.LastUpdated).Max();
            return dateReported;
        }

Error is:

There is already an open DataReader associated with this Command which must be closed first.

[EDIT]

stack trace added:

InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first.]
   System.Data.SqlClient.SqlInternalConnectionTds.ValidateConnectionForExecute(SqlCommand command) +5008639
   System.Data.SqlClient.SqlConnection.ValidateConnectionForExecute(String method, SqlCommand command) +23
   System.Data.SqlClient.SqlCommand.ValidateCommand(String method, Boolean async) +144
   System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) +87
   System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +32
   System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +141
   System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +12
   System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) +10
   System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior) +443

[EntityCommandExecutionException: An error occurred while executing the command definition. See the inner exception for details.]
   System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior) +479
   System.Data.Objects.Internal.ObjectQueryExecutionPlan.Execute(ObjectContext context, ObjectParameterCollection parameterValues) +683
   System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption) +119
   System.Data.Objects.ObjectQuery`1.System.Collections.Generic.IEnumerable<T>.GetEnumerator() +38
   System.Linq.Enumerable.Single(IEnumerable`1 source) +114
   System.Data.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__3(IEnumerable`1 sequence) +4
   System.Data.Objects.ELinq.ObjectQueryProvider.ExecuteSingle(IEnumerable`1 query, Expression queryRoot) +29
   System.Data.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute(Expression expression) +91
   System.Data.Entity.Internal.Linq.DbQueryProvider.Execute(Expression expression) +69
   System.Linq.Queryable.Max(IQueryable`1 source) +216
   CreditRegistry.Repositories.CreditRegistryRepository.DateLastUpdated(Int64 creditorRegistryId, String accountNo) in D:\Freelance Work\SuperExpert\CreditRegistry\CreditRegistry\Repositories\CreditRegistryRepository.cs:1497
   CreditRegistry.Repositories.CreditRegistryRepository.<AccountDetails>b__88(AccountsReport account, Int32 index) in D:\Freelance Work\SuperExpert\CreditRegistry\CreditRegistry\Repositories\CreditRegistryRepository.cs:1250
   System.Linq.<SelectIterator>d__7`2.MoveNext() +198
   System.Linq.Buffer`1..ctor(IEnumerable`1 source) +217
   System.Linq.<GetEnumerator>d__0.MoveNext() +96

Source: (StackOverflow)

Advertisements

Entity Framework 4 / POCO - Where to start? [closed]

I've been programming for a while and have used LINQ-To-SQL and LINQ-To-Entities before (although when using entities it has been on a Entity/Table 1-1 relationship - ie not much different than L2SQL)

I've been doing a lot of reading about Inversion of Control, Unit of Work, POCO and repository patterns and would like to use this methodology in my new applications.

Where I'm struggling is finding a clear, concise beginners guide for EF4 which doesn't assume knowledge of EF1.

The specific questions I need answered are:

Code first / model first? Pros/cons in regards to EF4 (ie what happens if I do code first, change the code at a later date and need to regenerate my DB model - Does the data get preserved and transformed or dropped?)

Assuming I'm going code-first (I'd like to see how EF4 converts that to a DB schema) how do I actually get started? Quite often I've seen articles with entity diagrams stating "So this is my entity model, now I'm going to ..." - Unfortunately, I'm unclear if they're created the model in the designer, saved it to generate code then stopped any further auto-code generation -or- They've coded (POCO)? classes and the somehow imported them into the deisgner view?

I suppose what I really need is an understanding of where the "magic" comes from and how to add it myself if I'm not just generating an EF model directly from a DB.

I'm aware the question is a little vague but I don't know what I don't know - So any input / correction / clarification appreciated.

Needless to say, I don't expect anyone to sit here and teach me EF - I'd just like some good tutorials/forums/blogs/etc. for complete entity newbies


Source: (StackOverflow)

Entity Framework Timeouts

I am getting timeouts using the Entity Framework (EF) when using a function import that takes over 30 seconds to complete. I tried the following and have not been able to resolve this issue:

I added Default Command Timeout=300000 to the connection string in the App.Config file in the project that has the EDMX file as suggested here: Entity Framework with MySQL - Timeout Expired while Generating Model

This is what my connection string looks like:

<add 
    name="MyEntityConnectionString" 
    connectionString="metadata=res://*/MyEntities.csdl|res://*/MyEntities.ssdl|res://*/MyEntities.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=trekdevbox;Initial Catalog=StarTrekDatabase;Persist Security Info=True;User ID=JamesTKirk;Password=IsFriendsWithSpock;MultipleActiveResultSets=True;Default Command Timeout=300000;&quot;" 
    providerName="System.Data.EntityClient" />

I tried setting the CommandTimeout in my repository directly like so:

private TrekEntities context = new TrekEntities();

public IEnumerable<TrekMatches> GetKirksFriends()
{
  this.context.CommandTimeout = 180;
  return this.context.GetKirksFriends();
}

What else can I do to get the EF from timing out? This only happens for very large datasets. Everything works fine with small datasets.

Here is one of the errors I'm getting:

System.Data.EntityCommandExecutionException: An error occurred while executing the command definition. See the inner exception for details. ---> System.Data.SqlClient.SqlException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.

OK - I got this working and it's silly what happened. I had both the connection string with "Default Command Timeout=300000" and the CommandTimeout set to 180; When I removed the Default Command Timeout from the connection string, it worked. So the answer is to manually set the CommandTimeout in your repository on your context object like so:

this.context.CommandTimeout = 180; Apparently setting the timeout settings in the connection string has no effect on it.


Source: (StackOverflow)

Entity Framework 4 - AddObject vs Attach

I have been working with Entity Framework 4 recently, and am slightly confused as to when to use ObjectSet.Attach, and ObjectSet.AddObject.

From my understanding:

  • Use "Attach" when an Entity already exists in the system
  • Use "AddObject" when creating a brand new Entity

So, if i'm creating a new Person, i do this.

var ctx = new MyEntities();
var newPerson = new Person { Name = "Joe Bloggs" };
ctx.Persons.AddObject(newPerson);
ctx.SaveChanges();

If i'm modifying an existing Person, i do this:

var ctx = new MyEntities();
var existingPerson = ctx.Persons.SingleOrDefault(p => p.Name = "Joe Bloggs" };
existingPerson.Name = "Joe Briggs";
ctx.SaveChanges();

Keep in mind, this is a very simple example. In reality i am using Pure POCO's (no code generation), Repository pattern (don't deal with ctx.Persons), and Unit of Work (don't deal with ctx.SaveChanges). But "under the covers", the above is what happens in my implementation.

Now, my question - I am yet to find a scenario where i have had to use Attach.

What am i missing here? When do we need to use Attach?

EDIT

Just to clarify, i'm looking for examples of when to use Attach over AddObject (or vice-versa).

EDIT 2

The below answer is correct (which i accepted), but thought i'd add another example where Attach would be useful.

In my above example for modifying an existing Person, two queries are actually being executed.

One to retrieve the Person (.SingleOrDefault), and another to perform the UPDATE (.SaveChanges).

If (for some reason), i already knew that "Joe Bloggs" existed in the system, why do an extra query to get him first? I could do this:

var ctx = new MyEntities();
var existingPerson = new Person { Name = "Joe Bloggs" };
ctx.Persons.Attach(existingPerson);
ctx.SaveChanges();

This will result in just an UPDATE statement being executed.


Source: (StackOverflow)

Entity Framework - Add Navigation Property Manually

I generated an Entity Framework Model (4.0) from my database. I did not design the database and do not have any control over the schema, but there are a few tables that do not have foreign key constraints defined, but there is an implicit relationship defined.

For example:

I have a table called People that has the following columns: GenderID RaceID

There are tables for both Gender and Race but there is no foreign key in the People table.

When I imported the model it did not add Navigation Properties for these relationships. I tried to add it manually but From Role and To Role are disabled. I'm not sure how to add the relationship myself. How do I do this?


Source: (StackOverflow)

ADO.NET DbContext Generator vs. ADO.NET Poco Entity Generator (ObjectContext)

I am about to start implementing the data access infrastructure of a project that was architected with an approach to DDD (it's my first attempt on DDD, so be gentle ;-) ).

I will be using Entity Framework. Until now, I was looking into the method teached by Julie Lerman on her great book, Programming Entity Framework, where ADO.NET POCO Entity Generator is used, with some changes to the T4 templates and some more custom code.
Today I started reading articles on EF4.1 and the ADO.NET DbContext Generator, using Database First approach, and I'm trying to decide with which one should I go.

DbContext and EF4.1's approach on DDD seems to be a nice, cleaner way than POCO Entities, but I'm afraid that it could lead to some issues in the near future, since EF4.1 is still in RC.

From ADO.NET team blog, I know that EF4.1 does not include:

  • Enum support
  • Spatial data type support
  • Stored Procedure support in Code First
  • Migration support in Code First
  • Customizable conventions in Code First

From my understanding, since I will be using Database First there is a smaller number of features that were not included.

In conclusion, my question is:
Can I replace POCO Entities Generator with EF4.1 DbContext Generator?


Source: (StackOverflow)

How should I edit an Entity Framework connection string?

I recently had to edit my app.config file to change the connection string for an Entity Framework data model (.edmx file). But I'd like to know...Is there a way to edit the EF connection string using the designer?

The original connection string is auto-generated by the Entity Data Model wizard. The connection string then cannot be changed - it remains disabled in the properties window of the .edmx designer. I like to avoid editing XML by hand if I can (in app.config), so I was wondering if there is a way to get back into the original wizard screen to make connection string changes and let the tool edit the app.config file for me.


Source: (StackOverflow)

The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid

I have a one entity framework object and when I add it to my project, the connectionstring is added to app.config in the connectionstring section, but when I want to create new entitycontext and use this connectionstring, this error appears


Source: (StackOverflow)

Is DbContext the same as DataContext?

I'm following a tutorial by Scott Gu that refers to a class named DbContext. I can't find it on any namespace on framework 4 and it seems to me it was renamed from CT4 DbContext to .net4 System.Data.Linq.DataContext. Is my assumption correct?


Source: (StackOverflow)

Unit testing with EF4 "Code First" and Repository

I am attempting to get a handle on Unit testing a very simple ASP.NET MVC test app I've built using the Code First approach in the latest EF4 CTP. I'm not very experience with Unit testing / mocking etc.

This is my Repository class:

public class WeightTrackerRepository
{
    public WeightTrackerRepository()
    {
        _context = new WeightTrackerContext();
    }

    public WeightTrackerRepository(IWeightTrackerContext context)
    {
        _context = context;
    }

    IWeightTrackerContext _context;

    public List<WeightEntry> GetAllWeightEntries()
    {
        return _context.WeightEntries.ToList();
    }

    public WeightEntry AddWeightEntry(WeightEntry entry)
    {
        _context.WeightEntries.Add(entry);
        _context.SaveChanges();
        return entry;
    }
}

This is IWeightTrackerContext

public interface IWeightTrackerContext
{
    DbSet<WeightEntry> WeightEntries { get; set; }
    int SaveChanges();
}

...and its implementation, WeightTrackerContext

public class WeightTrackerContext : DbContext, IWeightTrackerContext
{
    public DbSet<WeightEntry> WeightEntries { get; set; }
}

In my test, I have the following:

[TestMethod]
public void Get_All_Weight_Entries_Returns_All_Weight_Entries()
{
    // Arrange
    WeightTrackerRepository repos = new WeightTrackerRepository(new MockWeightTrackerContext());

    // Act
    List<WeightEntry> entries = repos.GetAllWeightEntries();

    // Assert
    Assert.AreEqual(5, entries.Count);
}

And my MockWeightTrackerContext:

class MockWeightTrackerContext : IWeightTrackerContext
{
    public MockWeightTrackerContext()
    {
        WeightEntries = new DbSet<WeightEntry>();
        WeightEntries.Add(new WeightEntry() { Date = DateTime.Parse("01/06/2010"), Id = 1, WeightInGrams = 11200 });
        WeightEntries.Add(new WeightEntry() { Date = DateTime.Parse("08/06/2010"), Id = 2, WeightInGrams = 11150 });
        WeightEntries.Add(new WeightEntry() { Date = DateTime.Parse("15/06/2010"), Id = 3, WeightInGrams = 11120 });
        WeightEntries.Add(new WeightEntry() { Date = DateTime.Parse("22/06/2010"), Id = 4, WeightInGrams = 11100 });
        WeightEntries.Add(new WeightEntry() { Date = DateTime.Parse("29/06/2010"), Id = 5, WeightInGrams = 11080 });
    }

    public DbSet<WeightEntry> WeightEntries { get;set; }

    public int SaveChanges()
    {
        throw new NotImplementedException();
    }
}

My problem occurs when I'm trying to build up some test data as I can't create a DbSet<> as it has no constructor. I get the feeling I'm barking up the wrong tree with my whole approach trying to mock my context. Any advice would be most welcome to this complete unit testing newbie.


Source: (StackOverflow)

How do I correctly set an association between two objects in the Entity Framework 4 Entitydesigner?

For a new project I'm trying to create my business classes first and create the real database tables later. Therefore I'm using the Entity Framework 4 Designer. A created a new "ADO.Net Entity Data model" file, with the extension .edmx.

I created two Entities:
alt text

I want to add a 1 to nc relation between Product -> Group. If I'd created the MSSQL database first, I would have added a column IDGroup to the Table Product and referenced Product.IDGroup to Group.IDGroup. As far as I can see, I can't add such association in the designer if I add a new Property called IDGroup to the Product Entity

This is how I add the mapping: alt text

Which results in:
alt text

Now the part what this question is about: If I add two tables from an existing MSSQL database to the edmx file, I'll get the compile error:

Error 3027: No mapping specified for the following EntitySet/AssociationSet - GroupSet, ProductSet

What does that error mean and what must I do to fix this? If I delete those two tables, I'll receive a warning instead:

Error 2062: No mapping specified for instances of the EntitySet and AssociationSet in the EntityContainer myContainer.

Something tells me, I'm doing this all wrong and this is just basic stuff. How can I do it right?


Source: (StackOverflow)

The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties

Using this code in Entity Framework I receive the following error. I need to get all the rows for a specific date, DateTimeStart is of type DataType in this format 2013-01-30 12:00:00.000

Any idea?

 var eventsCustom = eventCustomRepository.FindAllEventsCustomByUniqueStudentReference(userDevice.UniqueStudentReference)
                    .Where(x =>  x.DateTimeStart.Date == currentDateTime.Date);

And the error is:

base {System.SystemException} = {"The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported."}

Source: (StackOverflow)

Entity Framework 4 mapping fragment error when adding new entity scalar

I have an Entity Framework 4 model-first design. I create a first draft of my model in the designer and all was well. I compiled, generated database, etc.

Later on I tried to add a string scalar (Nullable = true) to one of my existing entities and I keep getting this type of error when I compile:

Error 3004: Problem in mapping fragments starting at line 569: No mapping specified for properties MyEntity.MyValue in Set MyEntities. An Entity with Key (PK) will not round-trip when: Entity is type [MyEntities.MyEntity]

I keep having to manually open the EDMX file and correct the XML whenever I add scalars.

Ideas on what's going on?


Source: (StackOverflow)

What's the difference(s) between .ToList(), .AsEnumerable(), AsQueryable()?

I know some diefferences of L2E and L2O which the first implements IQueryable and the second implements IEnumerable and my Q scope is within EF 5.

My Q is what's the technical difference(s) of Those 3 methods. I see that in many situations all of them work. I also see using combinations of them like .ToList().AsQueryable().

1) What those method exactly mean?

2) Is there any performance or other issue about them in comparison to others?

3) Why using for example .ToList().AsQueryable() instead of .AsQueryable()?

Thanks in advance


Source: (StackOverflow)