obtaing the GUID for an EntityReference using Plugins in DynamicsCRM - plugins

This question is in relation to a Plugin which I am now creating for Dynamics CRM 2011.
I have an entity which has 5 attributes. 1 of these attributes is a Lookup to another entity.
What I am trying to do with my Plugin is to retreive the Guid of the Lookup entity. Simple, right?
But no, It is giving me trouble, I have tried dozens of ways using EntityReference to obtain the guid but cannot. I have tried creating a preImage which failed too.
Here is a snippet of the CODE.
Entity entity = (Entity)context.InputParameters["Target"];
if (entity.LogicalName == "new_producttaxrate")
{
if (entity.Attributes.Contains("new_product"))
{
EntityReference ownerLookup = (EntityReference)entity.Attributes["new_product"];
productName = ownerLookup.Name;
Guid productId = ownerLookup.Id;
}
}
also came up with this
if (entity.Attributes.Contains("new_producttaxrateid"))
{
Guid myGuid = (Guid)entity.Attributes["new_producttaxrateid"];
EntityReference ownerLookup = new EntityReference("new_product", myGuid);
pid = ownerLookup.Id;
}
I keep getting this error
Unhandled Exception: System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: Condition for attribute 'new_producttaxrate.new_product': expected argument(s) of type 'System.Guid' but received 'System.DBNull'.Detail:
<OrganizationServiceFault xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/xrm/2011/Contracts">
<ErrorCode>-2147220989</ErrorCode>
<ErrorDetails xmlns:d2p1="http://schemas.datacontract.org/2004/07/System.Collections.Generic">
<KeyValuePairOfstringanyType>
<d2p1:key>CallStack</d2p1:key>
<d2p1:value xmlns:d4p1="http://www.w3.org/2001/XMLSchema" i:type="d4p1:string"> at Microsoft.Crm.Extensibility.VersionedPluginProxyStepBase.Execute(PipelineExecutionContext context)
at Microsoft.Crm.Extensibility.Pipeline.Execute(PipelineExecutionContext context)
at Microsoft.Crm.Extensibility.MessageProcessor.Execute(PipelineExecutionContext context)
at Microsoft.Crm.Extensibility.InternalMessageDispatcher.Execute(PipelineExecutionContext context)
at Microsoft.Crm.Extensibility.ExternalMessageDispatcher.ExecuteInternal(IInProcessOrganizationServiceFactory serviceFactory, IPlatformMessageDispatcherFactory dispatcherFactory, String messageName, String requestName, Int32 primaryObjectTypeCode, Int32 secondaryObjectTypeCode, ParameterCollection fields, CorrelationToken correlationToken, CallerOriginToken originToken, UserAuth userAuth, Guid callerId, Guid transactionContextId, Int32 invocationSource, Nullable`1 requestId, Version endpointVersion)
at Microsoft.Crm.Extensibility.OrganizationSdkServiceInternal.ExecuteRequest(OrganizationRequest request, CorrelationToken correlationToken, CallerOriginToken callerOriginToken, WebServiceType serviceType)
at Microsoft.Crm.Extensibility.OrganizationSdkServiceInternal.Execute(OrganizationRequest request, CorrelationToken correlationToken, CallerOriginToken callerOriginToken, WebServiceType serviceType)</d2p1:value>
</KeyValuePairOfstringanyType>
</ErrorDetails>
<Message>Condition for attribute 'new_producttaxrate.new_product': expected argument(s) of type 'System.Guid' but received 'System.DBNull'.</Message>
<Timestamp>2011-03-17T13:21:04.6999035Z</Timestamp>
<InnerFault i:nil="true" />
<TraceText>
[VATPlugin2: VATPlugin2.TaxRateValidation]
[4b0b7f5c-9950-e011-849d-000c292be099: VATPlugin2.TaxRateValidation: Create of new_producttaxrate]
</TraceText>
</OrganizationServiceFault>

if (entity.Attributes.Contains("new_product"))
{
productGUID = ((EntityReference)entity["new_product"]).Id;
Entity member = service.Retrieve("product", ((EntityReference)entity["new_product"]).Id, new ColumnSet(true));
if (member.Attributes.Contains("name"))
{
productName = member.Attributes["name"].ToString();
}
}

Related

Getting multiple errors during Database-Migration with EF6 and .NET 4.6.1

Getting the following errors:
"Validation failed for one or more entities. See 'EntityValidationErrors' property for more details." at line 89 of Configuration.cs
Line 89 is simply a context.SaveChanges();, at the end of the class file:
namespace Model.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<Model.ApplicationDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(ApplicationDbContext context)
{
SeedData.AdditionalSeed _AdditionalSeed = new SeedData.AdditionalSeed();
_AdditionalSeed.Seed_StateOrProvince(context);
_AdditionalSeed.Seed_CountryOrRegion(context);
_AdditionalSeed.Seed_ContactTypes(context);
_AdditionalSeed.Seed_CurrencyCodes(context);
_AdditionalSeed.Seed_Preferences_CalendarSettings_CalendarView(context);
_AdditionalSeed.Seed_Preferences_CalendarSettings_WeeklyView(context);
_AdditionalSeed.Seed_Preferences_CalendarSettings_WhatToShow(context);
_AdditionalSeed.Seed_Preferences_Calendar_FuturePastSettings(context);
_AdditionalSeed.Seed_Preferences_ItemsAndInventory_AdvancedInventory_Barcodes_CopyBarcodeFrom(context);
_AdditionalSeed.Seed_Preferences_ItemsAndInventory_UnitOfMeasureType(context);
_AdditionalSeed.Seed_Preferences_PayrollEmployees_EmployeeDefaults_PayFrequency(context);
_AdditionalSeed.Seed_Preferences_PayrollEmployees_EmployeeDefaults_SickAndVacationDefaults_AccuralPeriod(context);
_AdditionalSeed.Seed_Preferences_PayrollEmployees_EmployeeDefaults_Taxes_FilingStatus(context);
_AdditionalSeed.Seed_Preferences_ReportsAndGraphs_ReportPreferences_DatePreparedFormat(context);
_AdditionalSeed.Seed_Preferences_ReportsAndGraphs_ReportPreferences_PageNumberFormat(context);
_AdditionalSeed.Seed_Preferences_ReportsAndGraphs_ReportPreferences_PageLayout(context);
_AdditionalSeed.Seed_Preferences_SalesAndCustomers_InvoicePackingSlip(context);
_AdditionalSeed.Seed_Preferences_SalesAndCustomers_RoundingRules(context);
_AdditionalSeed.Seed_Preferences_SalesAndCustomers_Shippers(context);
_AdditionalSeed.Seed_Preferences_SalesTax_Intervals(context);
_AdditionalSeed.Seed_Preferences_SalesTax_SalesTaxCode(context);
_AdditionalSeed.Seed_Preferences_SendForms_SendMethod(context);
_AdditionalSeed.Seed_Preferences_SendForms_DeliveryMethod(context);
_AdditionalSeed.Seed_Preferences_SendForms_EmailTemplateCategoryList(context);
_AdditionalSeed.Seed_Preferences_TimeAndExpenses_WorkWeek(context);
_AdditionalSeed.Seed_Security_RoleMaster(context);
context.SaveChanges();
_AdditionalSeed.Seed_Security_AccountingRole(context);
_AdditionalSeed.Seed_Security_BankingRole(context);
_AdditionalSeed.Seed_Security_CentersRole(context);
_AdditionalSeed.Seed_Security_CompanyRole(context);
_AdditionalSeed.Seed_Security_CustomerAndReceivablesRole(context);
_AdditionalSeed.Seed_Security_EmployeesAndPayrollRole(context);
_AdditionalSeed.Seed_Security_FileRole(context);
_AdditionalSeed.Seed_Security_ListsRole(context);
_AdditionalSeed.Seed_Security_ReportsRole(context);
_AdditionalSeed.Seed_Security_SiteSettingsRole(context);
_AdditionalSeed.Seed_Security_TimeTrackingRole(context);
_AdditionalSeed.Seed_Security_VendorsAndPayablesRole(context);
_AdditionalSeed.Seed_TaxesFilingStatus(context);
_AdditionalSeed.Seed_EmploymentType(context);
_AdditionalSeed.Seed_EmployeeEmergencyContactType(context);
_AdditionalSeed.Seed_EmployeeEthnicity(context);
_AdditionalSeed.Seed_EmployeeMaritalStatus(context);
_AdditionalSeed.Seed_Salutations(context);
_AdditionalSeed.Seed_DefaultUnitUsedForTypes(context);
_AdditionalSeed.Seed_UnitOfMeasureDefaultType(context);
context.SaveChanges();
_AdditionalSeed.Seed_UnitOfMeasureDefaultBaseUnits(context);
context.SaveChanges();
_AdditionalSeed.Seed_UnitOfMeasureDefaultRelatedUnits(context);
context.SaveChanges();
_AdditionalSeed.Seed_Terms(context);
_AdditionalSeed.Seed_TaxForms(context);
context.SaveChanges();
_AdditionalSeed.Seed_TaxFormDetail(context);
_AdditionalSeed.Seed_AccountTypes(context);
context.SaveChanges();
_AdditionalSeed.Seed_Industries(context);
context.SaveChanges();
_AdditionalSeed.Seed_OrganizationTypes(context);
context.SaveChanges();
}
}
}
When I comment this line out I then get the following error:
"Sequence contains more than one element" at line 12 of TaxFormDetail.cs
The code for this class file is over 1200 lines so I will only supply the unique lines:
namespace Model.Migrations.SeedData
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
public partial class AdditionalSeed
{
public void Seed_TaxFormDetail(ApplicationDbContext context)
{
context.TaxFormDetail.AddOrUpdate(
r => new { r.TaxFormID, r.TaxCodeLineDescription },
new TaxFormDetailModel() { TaxCodeLineNumber = null, TaxCodeLineDescription = "Schedule F: Interest expense, mortgage", TaxFormID = context.TaxForms.FirstOrDefault(r => r.TaxForm.Equals("1040")).RecordID },
.....
new TaxFormDetailModel() { TaxCodeLineNumber = null, TaxCodeLineDescription = "Pt I-Unrel Bus Inc: Sch C, L3-Inc-real/pers prop", TaxFormID = context.TaxForms.FirstOrDefault(r => r.TaxForm.Equals("990-T")).RecordID }
);
}
}
}
My model for this table is as follows:
[Table(name: "TaxFormDetail")]
public class TaxFormDetailModel
{
[Key, Required, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid RecordID { get; set; }
public Guid TaxFormID { get; set; }
public string TaxCodeLineNumber { get; set; }
[MaxLength(255)]
public string TaxCodeLineDescription { get; set; }
}
I have read numerous google and SO results on these errors and nothing helps unless I have missed something.
EDIT
The only error I have is the stack trace as this is run by the Package Manager, There is no other way I know of of getting anything else:
System.InvalidOperationException: Sequence contains more than one element
at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source)
at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__2[TResult](IEnumerable`1 sequence)
at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable`1 query, Expression queryRoot)
at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[TResult](Expression expression)
at System.Data.Entity.Internal.Linq.DbQueryProvider.Execute[TResult](Expression expression)
at System.Linq.Queryable.SingleOrDefault[TSource](IQueryable`1 source, Expression`1 predicate)
at System.Data.Entity.Migrations.DbSetMigrationsExtensions.AddOrUpdate[TEntity](DbSet`1 set, IEnumerable`1 identifyingProperties, InternalSet`1 internalSet, TEntity[] entities)
at System.Data.Entity.Migrations.DbSetMigrationsExtensions.AddOrUpdate[TEntity](IDbSet`1 set, Expression`1 identifierExpression, TEntity[] entities)
at Model.Migrations.SeedData.AdditionalSeed.Seed_TaxFormDetail(ApplicationDbContext context) in Z:\_Profile Storage\Projects\Corporate.WEB\Model\Migrations\SeedData\TaxFormDetail.cs:line 12
at Model.Migrations.Configuration.Seed(ApplicationDbContext context) in Z:\_Profile Storage\Projects\Corporate.WEB\Model\Migrations\Configuration.cs:line 81
at System.Data.Entity.Migrations.DbMigrationsConfiguration`1.OnSeed(DbContext context)
at System.Data.Entity.Migrations.DbMigrator.SeedDatabase()
at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.SeedDatabase()
at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String targetMigration)
at System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClassc.<Update>b__b()
at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String targetMigration)
at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.Run()
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
at System.Data.Entity.Migrations.Design.ToolingFacade.Update(String targetMigration, Boolean force)
at System.Data.Entity.Migrations.UpdateDatabaseCommand.<>c__DisplayClass2.<.ctor>b__0()
at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
Sequence contains more than one element
I figured out a workaround for this situation.
For the "Validation failed for one or more entities. See 'EntityValidationErrors' property for more details." at line 89 of Configuration.cs error, I changed the seed method to check for existing data for that specific table (tax code) and if the table was empty, add records NOT add or update.
As far as "Sequence contains more than one element" at line 12 of TaxFormDetail.cs goes, I basically did the same thing.
Now every time I do an Update-Database PM command, I do not get any more errors.

Error when running Seed method using code first EF 6

I was trying to run the update-database command to insert some initial data in my database and I got and error. Here is my class:
[Table("NotAllowedDomain")]
public class NotAllowedDomain : Entity
{
[Key]
public int DomainId { get; set; }
public string Domain { get; set; }
}
and here is my Seed method:
protected override void Seed(DbContext context)
{
var notAllowedDomainsList = new List<NotAllowedDomain>
{
new NotAllowedDomain {Domain = "test.com"},
new NotAllowedDomain {Domain = "test1.com"},
new NotAllowedDomain {Domain = "test2.co"}
};
notAllowedDomainsList.ForEach(x => context.NotAllowedDomains.AddOrUpdate(n => n.Domain, x));
}
After the Add-Migration AddingNotAllowedDomains, I ran Update-Database and got this error:
Running Seed method.
System.InvalidOperationException: Saving or accepting changes failed because more than one entity of type 'Model.NotAllowedDomain' have the same primary key value. Ensure that explicitly set primary key values are unique. Ensure that database-generated primary keys are configured correctly in the database and in the Entity Framework model. Use the Entity Designer for Database First/Model First configuration. Use the 'HasDatabaseGeneratedOption" fluent API or 'DatabaseGeneratedAttribute' for Code First configuration.
at System.Data.Entity.Core.Objects.ObjectStateManager.FixupKey(EntityEntry entry)
at System.Data.Entity.Core.Objects.EntityEntry.AcceptChanges()
at System.Data.Entity.Core.Objects.EntityEntry.ChangeObjectState(EntityState requestedState)
at System.Data.Entity.Core.Objects.EntityEntry.ChangeState(EntityState state)
at System.Data.Entity.Internal.StateEntryAdapter.ChangeState(EntityState state)
at System.Data.Entity.Internal.InternalEntityEntry.set_State(EntityState value)
at System.Data.Entity.Infrastructure.DbEntityEntry.set_State(EntityState value)
at Repository.Pattern.Ef6.DataContext.SyncObjectsStatePreCommit()
at Repository.Pattern.Ef6.DataContext.SaveChanges()
at System.Data.Entity.Migrations.DbMigrator.SeedDatabase()
at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.SeedDatabase()
at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String targetMigration)
at System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClassc.<Update>b__b()
at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String targetMigration)
at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.Run()
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
at System.Data.Entity.Migrations.Design.ToolingFacade.Update(String targetMigration, Boolean force)
at System.Data.Entity.Migrations.UpdateDatabaseCommand.<>c__DisplayClass2.<.ctor>b__0()
at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
Saving or accepting changes failed because more than one entity of type 'Model.NotAllowedDomain' have the same primary key value. Ensure that explicitly set primary key values are unique. Ensure that database-generated primary keys are configured correctly in the database and in the Entity Framework model. Use the Entity Designer for Database First/Model First configuration. Use the 'HasDatabaseGeneratedOption" fluent API or 'DatabaseGeneratedAttribute' for Code First configuration.
Any help?
Do you have an EntityTypeConfiguration class for NotAllowedDomain?
public class NotAllowedDomainConfiguration : EntityTypeConfiguration<NotAllowedDomain>
{
public NotAllowedDomainConfiguration()
{
//Table
ToTable("NotAllowedDomains");
//Primary key
HasKey(e => e.DomainId);
//Properties
Property(e => e.DomainId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(e => e.Domain).HasMaxLength(100).IsRequired();
}
}
Reference this in your DbContext class by overriding the OnModelCreating method:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new NotAllowedDomainConfiguration());
base.OnModelCreating(modelBuilder);
}

Querying entities throws "Invalid Operation Exception" on enum field

I was just trying some features of entity framework 5 and kendo ui. I have a following ProductType enum
public enum ProductType {
[Description("Hazardous")]
Hazardous,
[Description("Non Hazardous")]
NonHazardous
}
This enum type is one of the field in the Product Entity.
[Table("Products")]
public class Product {
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
//Other Fields ...
[Required(ErrorMessage="Product Type is Required")]
public ProductType ProductType {get;set;}
}
The ProductType column in the underlying SQL Server Database is defined as (tinyint, not null).
I access list of Products in the following Controller Action of MVC
public ActionResult _ProductList(int pageSize, int skip) {
using (WorkUnit workUnit = new WorkUnit()) {
IQueryable<Product> products = workUnit.ProductRepository.GetAllProducts()
.Include(p => p.Category);
int total = products.Count();
List<Product> productList = products.ToList<Product>(); //Throws InvalidOperationException
return Json(new { total = total, data = productList }, JsonRequestBehavior.AllowGet);
}
}
Here is the description of the InvalidOperationException that is thrown on products.ToList() in the above controller action.
The 'ProductType' property on 'Product' could not be set to a 'Byte' value.
You must set this property to a non-null value of type 'ProductType'.
Any guesses why ToList() is throwing an InvalidOperationException.
Just for info, the Database existed previously, and the Entities were manually coded based on the Database as POCO's.
Edit
Here is the complete exception details
System.InvalidOperationException was unhandled by user code
HResult=-2146233079
Message=The 'ProductType' property on 'Product' could not be set to a 'Byte' value. You must set this property to a non-null value of type 'ProductType'.
Source=System.Data.Entity
StackTrace:
at System.Data.Common.Internal.Materialization.Shaper.ErrorHandlingValueReader`1.GetValue(DbDataReader reader, Int32 ordinal)
at System.Data.Common.Internal.Materialization.Shaper.GetPropertyValueWithErrorHandling[TProperty](Int32 ordinal, String propertyName, String typeName)
at lambda_method(Closure , Shaper )
at System.Data.Common.Internal.Materialization.Shaper.HandleEntityAppendOnly[TEntity](Func`2 constructEntityDelegate, EntityKey entityKey, EntitySet entitySet)
at lambda_method(Closure , Shaper )
at System.Data.Common.Internal.Materialization.Coordinator`1.ReadNextElement(Shaper shaper)
at System.Data.Common.Internal.Materialization.Shaper`1.SimpleEnumerator.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at KendoUI_Web_Demo.Controllers.HomeController._ProductList(Int32 pageSize, Int32 skip) in d:\Practice\ASP.NET_MVC\KendoUI_Web_Demo\KendoUI_Web_Demo\Controllers\HomeController.cs:line 52
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41()
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49()
InnerException:
There is a mismatch between the enum type which in your case is int based and your database where the column is byte (tinyint) based. You can fix this by setting the correct underlying type of your enum type:
public enum ProductType : byte
{
...
}

Entity Framework 4.3.1 to 5.0 RC - NullReferenceException during model creation

I've just switched our project to try Entity Framework 5.0 RC, running under .NET 4.0. Aside from updating namespace references, we haven't made any code changes. I'm getting the following the first time we try to access an entity framework object:
at System.Data.Entity.ModelConfiguration.Conventions.ForeignKeyNavigationPropertyAttributeConvention.System.Data.Entity.ModelConfiguration.Conventions.IEdmConvention<System.Data.Entity.Edm.EdmNavigationProperty>.Apply(EdmNavigationProperty navigationProperty, EdmModel model)
at System.Data.Entity.ModelConfiguration.Configuration.ConventionsConfiguration.EdmConventionDispatcher.Dispatch[TEdmDataModelItem](TEdmDataModelItem item)
at System.Data.Entity.ModelConfiguration.Configuration.ConventionsConfiguration.EdmConventionDispatcher.VisitEdmNavigationProperty(EdmNavigationProperty item)
at System.Data.Entity.Edm.Internal.DataModelItemVisitor.VisitCollection[T](IEnumerable`1 collection, Action`1 visitMethod)
at System.Data.Entity.Edm.Internal.EdmModelVisitor.VisitDeclaredNavigationProperties(EdmEntityType entityType, IEnumerable`1 navigationProperties)
at System.Data.Entity.ModelConfiguration.Configuration.ConventionsConfiguration.EdmConventionDispatcher.VisitEdmEntityType(EdmEntityType item)
at System.Data.Entity.Edm.Internal.DataModelItemVisitor.VisitCollection[T](IEnumerable`1 collection, Action`1 visitMethod)
at System.Data.Entity.Edm.Internal.EdmModelVisitor.VisitEntityTypes(EdmNamespace edmNamespace, IEnumerable`1 entityTypes)
at System.Data.Entity.Edm.Internal.EdmModelVisitor.VisitEdmNamespace(EdmNamespace item)
at System.Data.Entity.ModelConfiguration.Configuration.ConventionsConfiguration.EdmConventionDispatcher.VisitEdmNamespace(EdmNamespace item)
at System.Data.Entity.Edm.Internal.DataModelItemVisitor.VisitCollection[T](IEnumerable`1 collection, Action`1 visitMethod)
at System.Data.Entity.Edm.Internal.EdmModelVisitor.VisitNamespaces(EdmModel model, IEnumerable`1 namespaces)
at System.Data.Entity.Edm.Internal.EdmModelVisitor.VisitEdmModel(EdmModel item)
at System.Data.Entity.ModelConfiguration.Configuration.ConventionsConfiguration.EdmConventionDispatcher.VisitEdmModel(EdmModel item)
at System.Data.Entity.ModelConfiguration.Configuration.ConventionsConfiguration.EdmConventionDispatcher.Dispatch()
at System.Data.Entity.ModelConfiguration.Configuration.ConventionsConfiguration.ApplyModel(EdmModel model)
at System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo)
at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
at System.Data.Entity.Internal.InternalContext.Initialize()
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
at System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider()
at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable`1 source, Expression`1 predicate)
at BackEnd.Facade.Implementations.UserService.GetUserByUserName(String userName) in c:\Development\FundApps\Rapptr\src\FundApps.Rapptr.ServiceLayer\Facade\Implementations\UserService.cs:line 61
at FundApps.Rapptr.Common.Web.Security.WebUserContextModule.OnPostAuthenticateRequest(HttpContextBase context) in c:\Development\FundApps\Rapptr\src\FundApps.Rapptr.Common.Web\Security\WebUserContextModule.cs:line 54
at FundApps.Common.Mvc.BaseHttpModule.<Init>b__1(Object sender, EventArgs e) in c:\Development\FundApps\Rapptr\src\FundApps.Common.Mvc\BaseHttpModule.cs:line 14
at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Does anyone have any suggestions as to what might cause this and how to narrow it down?
UPDATE: This bug was fixed in EF5 RTM.
This is a bug in EF5. It happens when you have a 1:1 relationship and also use the ForeignKey attribute to explicitly specify the FK. For example:
public class OneToOneResult
{
public int OneToOneResultId { get; set; }
[ForeignKey("OneToOneResultId")]
public virtual OneToOneResultDetail Detail { get; set; }
}
public class OneToOneResultDetail
{
[Key]
public int OneToOneResultId { get; set; }
public DateTime DataDate { get; set; }
}
In OnModelCreating:
modelBuilder.Entity<OneToOneResult>()
.HasRequired(r => r.Detail)
.WithRequiredPrincipal();
The workaround is to remove the ForeignKey attribute. It is not needed in this case because the 1:1 relationship must be PK to PK since that is all that EF supports in this case.

EF Code First CTP5 - Using the name of the property as column name for foreign key

Given the following model:
public class Foo
{
public int Id { get; set;}
public Bar TheBar { get; set; }
}
public class Bar
{
public int Id { get; set;}
}
EF tries to generate the FK column as BarId.
How can make it use TheBar?
I've tried the following:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Foo>()
.HasOptional(x => x.Bar)
.WithMany()
.IsIndependent()
.Map(x => x.MapKey(bar => bar.Id, "TheBar"));
}
But I get the following exception when trying to use the context:
Exception has been thrown by the target of an invocation.
---> System.InvalidOperationException: Sequence contains more than one matching element
Server stack trace:
at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source, Func`2 predicate)
at System.Data.Entity.ModelConfiguration.Configuration.Properties.Navigation.IndependentAssociationMappingConfiguration`1.Configure(DbAssociationSetMapping associationSetMapping)
at System.Data.Entity.ModelConfiguration.Configuration.Properties.Navigation.NavigationPropertyConfiguration.Configure(DbDatabaseMapping databaseMapping)
at System.Data.Entity.ModelConfiguration.Utilities.IEnumerableExtensions.Each[T](IEnumerable`1 ts, Action`1 action)
at System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.ConfigureAssociationMappings(DbDatabaseMapping databaseMapping)
at System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.Configure(DbEntityTypeMapping entityTypeMapping, DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest)
at System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.Configure(DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest)
at System.Data.Entity.ModelConfiguration.ModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo, Boolean validateModel)
at System.Data.Entity.ModelConfiguration.ModelBuilder.Build(DbConnection providerConnection)
at System.Data.Entity.Internal.LazyInternalContext.CreateModel()
at System.Lazy`1.CreateValue()
Exception rethrown at [0]:
at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source, Func`2 predicate)
at System.Data.Entity.ModelConfiguration.Configuration.Properties.Navigation.IndependentAssociationMappingConfiguration`1.Configure(DbAssociationSetMapping associationSetMapping)
at System.Data.Entity.ModelConfiguration.Configuration.Properties.Navigation.NavigationPropertyConfiguration.Configure(DbDatabaseMapping databaseMapping)
at System.Data.Entity.ModelConfiguration.Utilities.IEnumerableExtensions.Each[T](IEnumerable`1 ts, Action`1 action)
at System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.ConfigureAssociationMappings(DbDatabaseMapping databaseMapping)
at System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.Configure(DbEntityTypeMapping entityTypeMapping, DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest)
at System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.Configure(DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest)
at System.Data.Entity.ModelConfiguration.ModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo, Boolean validateModel)
at System.Data.Entity.ModelConfiguration.ModelBuilder.Build(DbConnection providerConnection)
at System.Data.Entity.Internal.LazyInternalContext.CreateModel()
at System.Lazy`1.CreateValue()
at System.Lazy`1.LazyInitValue()
at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet`1.get_Provider()
at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable`1 source)
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle._InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeType typeOwner)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
The error was caused by a bug in CTP5. If the Id property was defined in a base class (which is not shown in the code above because I didn't think it was related), it breaks.
I solved it by defining a base interface, but keeping the Id in each class.
You want the MapKey method in the fluent interface.
Alternately, if you do this throughout your model, CTP 5 has pluggable conventions, although this is, AFAIK, not well-documented yet.