The entity type <class> is not part of the model for the current context - entity-framework

This is a MODEL first approach. I have already researched this extensiely and have not come up with an answer. I have tried all the suggestions at the following links:
This appears to be the same problem but with no resolution
The entity type <classname> is not part of the model for the current context
These are the links I have already researched so please don't answer as duplicate of ----
EF 4.1 Code First error - The entity type SomeType is not part of the model for the current context
The entity type is not part of the model, EF 5
Here is the EDMX (Abbreviated for brevity):
<?xml version="1.0" encoding="utf-8"?>
<edmx:Edmx Version="2.0" xmlns:edmx="http://schemas.microsoft.com/ado/2008/10/edmx">
<!-- EF Runtime content -->
<edmx:Runtime>
<!-- SSDL content -->
<edmx:StorageModels>
<Schema Namespace="Insight_Model.Store" Alias="Self" Provider="System.Data.SqlClient" ProviderManifestToken="2008" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" xmlns="http://schemas.microsoft.com/ado/2009/02/edm/ssdl">
<EntityContainer Name="Insight_ModelStoreContainer">
<EntitySet Name="vwCompanyHeader" EntityType="Insight_Model.Store.vwCompanyHeader" store:Type="Views" store:Schema="dbo" store:Name="vwCompanyHeader">
<DefiningQuery>SELECT
[vwCompanyHeader].[ID] AS [ID],
[vwCompanyHeader].[Name] AS [Name],
[vwCompanyHeader].[Active] AS [Active],
[vwCompanyHeader].[Creator] AS [Creator],
[vwCompanyHeader].[Created] AS [Created],
[vwCompanyHeader].[Modifier] AS [Modifier],
[vwCompanyHeader].[Modified] AS [Modified]
FROM [dbo].[vwCompanyHeader] AS [vwCompanyHeader]</DefiningQuery>
</EntitySet>
<EntitySet Name="vwWorkOrderHeader" EntityType="Insight_Model.Store.vwWorkOrderHeader" store:Type="Views" store:Schema="dbo" store:Name="vwWorkOrderHeader">
<DefiningQuery>SELECT
[vwWorkOrderHeader].[ID] AS [ID],
[vwWorkOrderHeader].[Active] AS [Active],
[vwWorkOrderHeader].[Name] AS [Name],
[vwWorkOrderHeader].[Creator] AS [Creator],
[vwWorkOrderHeader].[Created] AS [Created],
[vwWorkOrderHeader].[Modifier] AS [Modifier],
[vwWorkOrderHeader].[Modified] AS [Modified],
[vwWorkOrderHeader].[Leader] AS [Leader],
[vwWorkOrderHeader].[LeadTakenDate] AS [LeadTakenDate],
[vwWorkOrderHeader].[ProjectID] AS [ProjectID],
[vwWorkOrderHeader].[ProjectName] AS [ProjectName],
[vwWorkOrderHeader].[WorkOrderStatus] AS [WorkOrderStatus],
[vwWorkOrderHeader].[WorkOrderSubStatus] AS [WorkOrderSubStatus],
[vwWorkOrderHeader].[WorkOrderType] AS [WorkOrderType],
[vwWorkOrderHeader].[WorkOrderSubType] AS [WorkOrderSubType],
[vwWorkOrderHeader].[WorkOrderPriority] AS [WorkOrderPriority],
[vwWorkOrderHeader].[RefNumber] AS [RefNumber],
[vwWorkOrderHeader].[Request] AS [Request]
FROM [dbo].[vwWorkOrderHeader] AS [vwWorkOrderHeader]</DefiningQuery>
</EntitySet>
</EntityContainer>
<EntityType Name="vwCompanyHeader">
<Key>
<PropertyRef Name="ID" />
</Key>
<Property Name="ID" Type="int" Nullable="false" />
<Property Name="Name" Type="varchar" Nullable="false" MaxLength="50" />
<Property Name="Active" Type="bit" Nullable="false" />
<Property Name="Creator" Type="varchar" Nullable="false" MaxLength="51" />
<Property Name="Created" Type="date" Nullable="false" />
<Property Name="Modifier" Type="varchar" Nullable="false" MaxLength="51" />
<Property Name="Modified" Type="date" Nullable="false" />
</EntityType>
<EntityType Name="vwWorkOrderHeader">
<Key>
<PropertyRef Name="ID" />
</Key>
<Property Name="ID" Type="int" Nullable="false" />
<Property Name="Active" Type="bit" Nullable="false" />
<Property Name="Name" Type="varchar" Nullable="false" MaxLength="15" />
<Property Name="Creator" Type="varchar" Nullable="false" MaxLength="51" />
<Property Name="Created" Type="date" Nullable="false" />
<Property Name="Modifier" Type="varchar" Nullable="false" MaxLength="51" />
<Property Name="Modified" Type="date" Nullable="false" />
<Property Name="Leader" Type="varchar" Nullable="false" MaxLength="51" />
<Property Name="LeadTakenDate" Type="date" Nullable="false" />
<Property Name="ProjectID" Type="int" Nullable="false" />
<Property Name="ProjectName" Type="varchar" Nullable="false" MaxLength="15" />
<Property Name="WorkOrderStatus" Type="varchar" Nullable="false" MaxLength="35" />
<Property Name="WorkOrderSubStatus" Type="varchar" Nullable="false" MaxLength="35" />
<Property Name="WorkOrderType" Type="varchar" Nullable="false" MaxLength="35" />
<Property Name="WorkOrderSubType" Type="varchar" Nullable="false" MaxLength="35" />
<Property Name="WorkOrderPriority" Type="varchar" Nullable="false" MaxLength="35" />
<Property Name="RefNumber" Type="varchar" Nullable="false" MaxLength="25" />
<Property Name="Request" Type="varchar" Nullable="false" MaxLength="1500" />
</EntityType>
</Schema></edmx:StorageModels>
<!-- CSDL content -->
<edmx:ConceptualModels>
<Schema Namespace="Insight_Model" Alias="Self" xmlns:annotation="http://schemas.microsoft.com/ado/2009/02/edm/annotation" xmlns="http://schemas.microsoft.com/ado/2008/09/edm">
<EntityContainer Name="Insight_Entities" annotation:LazyLoadingEnabled="false">
<EntitySet Name="CompanyHeaders" EntityType="Insight_Model.CompanyHeader" />
<EntitySet Name="WorkOrderHeaders" EntityType="Insight_Model.WorkOrderHeader" />
</EntityContainer>
<EntityType Name="CompanyHeader">
<Key>
<PropertyRef Name="ID" />
</Key>
<Property Type="String" Name="Name" MaxLength="50" FixedLength="false" Unicode="false" Nullable="false" />
<Property Type="Boolean" Name="Active" Nullable="false" />
<Property Type="String" Name="Creator" Nullable="false" MaxLength="51" FixedLength="false" Unicode="false" />
<Property Type="DateTime" Name="Created" Nullable="false" />
<Property Type="String" Name="Modifier" Nullable="false" MaxLength="51" FixedLength="false" Unicode="false" />
<Property Type="DateTime" Name="Modified" Nullable="false" />
<Property Type="Int32" Name="ID" Nullable="false" />
</EntityType>
<EntityType Name="WorkOrderHeader">
<Key>
<PropertyRef Name="ID" />
</Key>
<Property Type="Int32" Name="ID" Nullable="false" />
<Property Type="Boolean" Name="Active" Nullable="false" />
<Property Type="String" Name="Name" Nullable="false" MaxLength="15" FixedLength="false" Unicode="false" />
<Property Type="String" Name="Creator" Nullable="false" MaxLength="51" FixedLength="false" Unicode="false" />
<Property Type="DateTime" Name="Created" Nullable="false" />
<Property Type="String" Name="Modifier" Nullable="false" MaxLength="51" FixedLength="false" Unicode="false" />
<Property Type="DateTime" Name="Modified" Nullable="false" />
<Property Type="String" Name="Leader" Nullable="false" MaxLength="51" FixedLength="false" Unicode="false" />
<Property Type="DateTime" Name="LeadTakenDate" Nullable="false" />
<Property Type="Int32" Name="ProjectID" Nullable="false" />
<Property Type="String" Name="ProjectName" Nullable="false" MaxLength="15" FixedLength="false" Unicode="false" />
<Property Type="String" Name="WorkOrderStatus" Nullable="false" MaxLength="35" FixedLength="false" Unicode="false" />
<Property Type="String" Name="WorkOrderSubStatus" Nullable="false" MaxLength="35" FixedLength="false" Unicode="false" />
<Property Type="String" Name="WorkOrderType" Nullable="false" MaxLength="35" FixedLength="false" Unicode="false" />
<Property Type="String" Name="WorkOrderSubType" Nullable="false" MaxLength="35" FixedLength="false" Unicode="false" />
<Property Type="String" Name="WorkOrderPriority" Nullable="false" MaxLength="35" FixedLength="false" Unicode="false" />
<Property Type="String" Name="RefNumber" MaxLength="25" Nullable="false" FixedLength="false" Unicode="false" />
<Property Type="String" Name="Request" Nullable="false" MaxLength="1500" FixedLength="false" Unicode="false" />
</EntityType>
</Schema>
</edmx:ConceptualModels>
<!-- C-S mapping content -->
<edmx:Mappings>
<Mapping Space="C-S" xmlns="http://schemas.microsoft.com/ado/2008/09/mapping/cs">
<EntityContainerMapping StorageEntityContainer="Insight_ModelStoreContainer" CdmEntityContainer="Insight_Entities">
<EntitySetMapping Name="CompanyHeaders">
<EntityTypeMapping TypeName="Insight_Model.CompanyHeader">
<MappingFragment StoreEntitySet="vwCompanyHeader">
<ScalarProperty Name="ID" ColumnName="ID" />
<ScalarProperty Name="Modified" ColumnName="Modified" />
<ScalarProperty Name="Modifier" ColumnName="Modifier" />
<ScalarProperty Name="Created" ColumnName="Created" />
<ScalarProperty Name="Creator" ColumnName="Creator" />
<ScalarProperty Name="Active" ColumnName="Active" />
<ScalarProperty Name="Name" ColumnName="Name" />
</MappingFragment>
</EntityTypeMapping>
</EntitySetMapping>
<EntitySetMapping Name="WorkOrderHeaders">
<EntityTypeMapping TypeName="Insight_Model.WorkOrderHeader">
<MappingFragment StoreEntitySet="vwWorkOrderHeader">
<ScalarProperty Name="Request" ColumnName="Request" />
<ScalarProperty Name="RefNumber" ColumnName="RefNumber" />
<ScalarProperty Name="WorkOrderPriority" ColumnName="WorkOrderPriority" />
<ScalarProperty Name="WorkOrderSubType" ColumnName="WorkOrderSubType" />
<ScalarProperty Name="WorkOrderType" ColumnName="WorkOrderType" />
<ScalarProperty Name="WorkOrderSubStatus" ColumnName="WorkOrderSubStatus" />
<ScalarProperty Name="WorkOrderStatus" ColumnName="WorkOrderStatus" />
<ScalarProperty Name="ProjectName" ColumnName="ProjectName" />
<ScalarProperty Name="ProjectID" ColumnName="ProjectID" />
<ScalarProperty Name="LeadTakenDate" ColumnName="LeadTakenDate" />
<ScalarProperty Name="Leader" ColumnName="Leader" />
<ScalarProperty Name="Modified" ColumnName="Modified" />
<ScalarProperty Name="Modifier" ColumnName="Modifier" />
<ScalarProperty Name="Created" ColumnName="Created" />
<ScalarProperty Name="Creator" ColumnName="Creator" />
<ScalarProperty Name="Name" ColumnName="Name" />
<ScalarProperty Name="Active" ColumnName="Active" />
<ScalarProperty Name="ID" ColumnName="ID" />
</MappingFragment>
</EntityTypeMapping>
</EntitySetMapping>
</EntityContainerMapping>
</Mapping>
</edmx:Mappings>
The repository code:
Imports System.Linq.Expressions
Imports System.Data.Entity.Infrastructure
Imports System.Data.Entity
Public Class Repository(Of T As {Class, IEntity})
Implements IRepository(Of T)
#Region "Attributes"
Private objectContext As IDatabaseContext
Protected objectSet As IDbSet(Of T)
#End Region
Public Sub New(objContext As IDatabaseContext)
objectContext = objContext
objectSet = objectContext.Set(Of T)()
End Sub
Public Function FindAll() As IQueryable(Of T) Implements IRepository(Of T).FindAll
Return objectSet
End Function
Public Function FindWhere(predicate As Expressions.Expression(Of System.Func(Of T, Boolean))) As System.Linq.IQueryable(Of T) Implements Interfaces.IRepository(Of T).FindWhere
Return objectSet.Where(predicate)
End Function
Public Function FindById(id As Integer) As T Implements IRepository(Of T).FindById
Return objectSet.Single(Function(o) o.ID = id)
End Function
Public Sub Add(newEntity As T) Implements IRepository(Of T).Add
objectSet.Add(newEntity)
End Sub
Public Sub Remove(entity As T) Implements IRepository(Of T).Remove
objectSet.Remove(entity)
End Sub
Public Function Count(Optional predicate As Expression(Of Func(Of T, Boolean)) = Nothing) As Integer Implements IRepository(Of T).Count
Return If((predicate Is Nothing), objectSet.Count, objectSet.Where(predicate).Count)
End Function
Public Function Exist(Optional predicate As Expression(Of Func(Of T, Boolean)) = Nothing) As Boolean Implements IRepository(Of T).Exist
Return If((predicate Is Nothing), objectSet.Any, objectSet.Where(predicate).Any)
End Function
End Class
The DatabaseContext code:
Imports System.Data.Entity
Imports Insight.DataLayer.Interfaces
Imports System.Data.Objects
Imports System.Configuration
Public Class DatabaseContext
Inherits DbContext
Implements IDatabaseContext
Const defaultConnectStringName = "Insight_Entities"
Public Sub New()
Me.New(ConfigurationManager.ConnectionStrings(defaultConnectStringName).ConnectionString)
End Sub
Public Sub New(connectionString As String)
MyBase.New(connectionString)
MyBase.Configuration.LazyLoadingEnabled = False
MyBase.Configuration.ProxyCreationEnabled = False
End Sub
Public Overloads Sub SaveChanges() Implements Interfaces.IDatabaseContext.SaveChanges
MyBase.SaveChanges()
End Sub
Public Overloads Function [Set](Of T As Class)() As System.Data.Entity.IDbSet(Of T) Implements Interfaces.IDatabaseContext.Set
Return MyBase.Set(Of T)()
End Function
End Class
And the 2 class files:
WorkOrderHeader:
Imports System.ComponentModel.DataAnnotations
Imports System.Collections.ObjectModel
Imports System.Runtime.Serialization
Imports System.Data.Services.Common
Partial Public Class WorkOrderHeader
Inherits DataTransferObjectHeaderBase
Public Sub New()
End Sub
Public Sub New(iID As Integer, sName As String, bActive As Boolean, sCreator As String, dtCreated As DateTime, sModifier As String, dtModified As DateTime, sLeader As String, dtLeadTaken As Date, iProjectID As Integer, sProjectName As String, sWorkOrderStatus As String, sWorkOrderSubStatus As String, sWorkOrderType As String, sWorkOrderSubType As String, sWorkOrderPriority As String, sRequest As String)
Me.New(iID, sName, bActive, sCreator, dtCreated, sModifier, dtModified, sLeader, dtLeadTaken, iProjectID, sProjectName, sWorkOrderStatus, sWorkOrderSubStatus, sWorkOrderType, sWorkOrderSubType, sWorkOrderPriority, "", sRequest)
End Sub
Public Sub New(iID As Integer, sName As String, bActive As Boolean, sCreator As String, dtCreated As DateTime, sModifier As String, dtModified As DateTime, sLeader As String, dtLeadTaken As Date, iProjectID As Integer, sProjectName As String, sWorkOrderStatus As String, sWorkOrderSubStatus As String, sWorkOrderType As String, sWorkOrderSubType As String, sWorkOrderPriority As String, sRefNumber As String, sRequest As String)
ID = iID
Name = sName
Active = bActive
Creator = sCreator
Created = dtCreated
Modifier = sModifier
Modified = dtModified
Leader = sLeader
LeadTaken = dtLeadTaken
ProjectID = iProjectID
ProjectName = sProjectName
WorkOrderStatus = sWorkOrderStatus
WorkOrderSubStatus = sWorkOrderSubStatus
WorkOrderType = sWorkOrderType
WorkOrderSubType = sWorkOrderSubType
WorkOrderPriority = sWorkOrderPriority
RefNumber = sRefNumber
Request = sRequest
End Sub
<DataMember()> _
Public Property Leader() As String
Get
Return _leader
End Get
Set(value As String)
_leader = value
End Set
End Property
Private _leader As String
<DataMember()> _
Public Property LeadTaken() As Date
Get
Return _leadTaken
End Get
Set(value As Date)
_leadTaken = value
End Set
End Property
Private _leadTaken As Date
<DataMember()> _
Public Property ProjectID() As Int32
Get
Return _projectID
End Get
Set(value As Int32)
If (_projectID <> value) Then
_projectID = value
End If
End Set
End Property
Private _projectID As Int32
<DataMember()> _
Public Property ProjectName() As String
Get
Return _projectName
End Get
Set(value As String)
If (_projectName <> value) Then
_projectName = value
End If
End Set
End Property
Private _projectName As String
<DataMember()> _
Public Property WorkOrderStatus() As String
Get
Return _workOrderStatus
End Get
Set(value As String)
_workOrderStatus = value
End Set
End Property
Private _workOrderStatus As String
<DataMember()> _
Public Property WorkOrderSubStatus() As String
Get
Return _workOrderSubStatus
End Get
Set(value As String)
_workOrderSubStatus = value
End Set
End Property
Private _workOrderSubStatus As String
<DataMember()> _
Public Property WorkOrderType() As String
Get
Return _workOrderType
End Get
Set(value As String)
_workOrderType = value
End Set
End Property
Private _workOrderType As String
<DataMember()> _
Public Property WorkOrderSubType() As String
Get
Return _workOrderSubType
End Get
Set(value As String)
_workOrderSubType = value
End Set
End Property
Private _workOrderSubType As String
<DataMember()> _
Public Property WorkOrderPriority() As String
Get
Return _workOrderPriority
End Get
Set(value As String)
_workOrderPriority = value
End Set
End Property
Private _workOrderPriority As String
<DataMember()> _
Public Property RefNumber() As String
Get
Return _refNumber
End Get
Set(value As String)
_refNumber = value
End Set
End Property
Private _refNumber As String
<DataMember()> _
Public Property Request() As String
Get
Return _request
End Get
Set(value As String)
_request = value
End Set
End Property
Private _request As String
End Class
#End Region
CompanyHeader:
Imports System.ComponentModel.DataAnnotations
Imports System.Collections.ObjectModel
Imports System.Runtime.Serialization
Imports System.Data.Services.Common
<DataServiceKey("ID")> _
<MetadataTypeAttribute(GetType(CompanyHeader.CompanyHeaderMetadata))> _
Partial Public Class CompanyHeader
Inherits DataTransferObjectHeaderBase
Friend NotInheritable Class CompanyHeaderMetadata
'Metadata classes are not meant to be instantiated.
Private Sub New()
MyBase.New()
End Sub
<DataMember()> _
Public Property Active As Boolean
<DataMember()> _
Public Property ID As Integer
<DataMember()> _
Public Property Created As DateTime
<DataMember()> _
Public Property Creator As String
<DataMember()> _
Public Property Modified As DateTime
<DataMember()> _
Public Property Modifier As String
<DataMember()> _
Public Property Name As String
End Class
Public Sub New()
End Sub
Public Sub New(iID As Integer, sName As String, bActive As Boolean, sCreator As String, dtCreated As DateTime, sModifier As String, dtModified As DateTime)
ID = iID
Name = sName
Active = bActive
Creator = sCreator
Created = dtCreated
Modifier = sModifier
Modified = dtModified
End Sub
End Class
Unit Test Code:
<TestMethod()> _
Public Sub WorkOrderServiceTests_TestConnectivityThruService5()
Dim woService As New DatabaseContext
Dim woHeaders = New Repository(Of WorkOrderHeader)(woService)
Dim woTests = New Repository(Of WorkOrderTest)(woService)
Dim coHeaders = New Repository(Of CompanyHeader)(woService)
Assert.IsTrue(woHeaders.Count <> 0)
End Sub
Things I have tried to resolve the issue:
1) Checked database - Both queries return data correctly.
select * from vwWorkOrderHeader
select * from vwCompanyHeader
2) Deleted WorkOrderHeader from the EDMX then recreated it from database.
3) MOQed out the DBContext to make sure that it isn't the service query doing something funny. This correctly returns the object, so it means that it is something at the context level or below.
4) Stepped through both tests to ensure that they use the same method of building the context - Thy do.
4) Stepped through both tests to ensure that they use the same method of building the repository - Thy do.
5) The only difference is during the following Function of DatabaseContext:
Public Overloads Function [Set](Of T As Class)() As System.Data.Entity.IDbSet(Of T) Implements Interfaces.IDatabaseContext.Set
Return MyBase.Set(Of T)()
End Function
The WorkOrderHeader code has the following in the watch for MyBase.Set(Of T)()
{System.Data.Entity.DbSet(Of Insight.Model.WorkOrderHeader)} System.Data.Entity.DbSet(Of Insight.Model.WorkOrderHeader)
The CompanyHeader code has the following in the watch for MyBase.Set(Of T)()
{SELECT [Extent1].[Name] AS [Name], [Extent1].[Active] AS [Active], [Extent1].[Creator] AS [Creator], [Extent1].[Created] AS [Created], [Extent1].[Modifier] AS [Modifier], [Extent1].[Modified] AS [Modified], [Extent1].[ID] AS [ID] FROM (SELECT [vwCompanyHeader].[ID] AS [ID], [vwCompanyHeader].[Name] AS [Name], [vwCompanyHeader].[Active] AS [Active], [vwCompanyHeader].[Creator] AS [Creator], [vwCompanyHeader].[Created] AS [Created], [vwCompanyHeader].[Modifier] AS [Modifier], [vwCompanyHeader].[Modified] AS [Modified] FROM [dbo].[vwCompanyHeader] AS [vwCompanyHeader]) AS [Extent1]} System.Data.Entity.DbSet(Of Insight.Model.CompanyHeader)
I am at a complete loss on this one and am entering my 3rd day of working on the same problem. I am hoping that some fresh eyes on the problem might see an error that I have made or point me in a direction of testing the problem that I have not thought of.
UPDATE:
I removed the service code to ensure it was something in the DBContext. I have isolated the service out of the equation so that only the repositories are being used and they are all using the same DatabaseContext, so it can't be anything related to the connection string. I verified that in the Model Browser under Insight_Model/EntityContainer:Insight_Entities/Entity Sets/WorkOrderHeaders exists and that under Insight_Model/Entity Types/WorkOrderHeader exists. It almost appears as though the DatabaseContext isn't even attempting to query the conceptual model for the entity set.

After 3 (4) days (depending on how you view days, I separate days by when I sleep and not necessarily when the sun goes down/comes up), I found the answer. In the EDMX file above, I have a column named LeadTakenDate, in the WorkOrderHeader class, I used the field name LeadTaken. This was a stupid error on my part.
How can this benefit you possibly? Here is how I resolved the problem:
First I isolated the problem to exactly one area by MOQing out parts to see how far down the rabbit hole the problem was. Once I figured out the problem was in the DatabaseContext, I wrote a test case that created a working and a non working use case. This isolated the problem and allowed me to test theories to fix it quicker. I tried a thousand different things before trying to use the EF 5.x persistance ignorant poco generator. I commented out all of my code in the WorkOrderHeader class and copied the generated code in. Reran my tests and they worked, so I started uncommenting my properties and commenting out the generated code then rerunning my test until I hit the appropriate property.
The error message is cryptic enough that is can be very difficult to trouble shoot.

Related

SAPUI5 - mockup server

I'm following this Mockup Server tutorial for SAPUI5. But I'm not able to retrieve the data and set it to my model. Here's what I do:
I have slightly changed the data so, so two things have to be changed:
json data - Person.json:
{ "id":1,
"first_name":"Chris",
"last_name":"Johnston", "email":"cjohnston0#dailymotion.com", "gender":"Male", "ip_address":"119.220.205.173" }
emphasized text
``
<edmx:Edmx Version="1.0"
xmlns:edmx="http://schemas.microsoft.com/ado/2007/06/edmx"/>
<edmx:DataServices m:DataServiceVersion="1.0"
m:MaxDataServiceVersion="3.0">
xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
<Schema Namespace="PersonsData" xmlns="http://schemas.microsoft.com/ado/2008/09/edm">
<EntityType Name="Person">
<Key>
<PropertyRef Name="id"/>
</Key>
<Property name="id" Type="Edm.Int16" Nullable="false" />
<Property Name="first_name" Type="Edm.String" Nullable="false" MaxLength="40" FixedLength="false" Unicode="true"/>
<Property Name="last_name" Type="Edm.String" Nullable="false" MaxLength="40" FixedLength="false" Unicode="true"/>
<Property Name="email" Type="Edm.String" Nullable="false"/>
<Property Name="gender" Type="Edm.String" Nullable="false" MaxLength="40" FixedLength="false"/>
<Property Name="ip_address" Type="Edm.String" Nullable="false" MaxLength="40" FixedLength="false" Unicode="true"/>
</EntityType>
</Schema>
<Schema Namespace="databinding.PersonsData.Model" xmlns="http://schemas.microsoft.com/ado/2008/09/edm">
<EntityContainer Name="PersonEntities" m:IsDefaultEntityContainer="true" p6:LazyLoadingEnabled="true"
xmlns:p6="http://schemas.microsoft.com/ado/2009/02/edm/annotation">
<EntitySet Name="Persons" EntityType="PersonsData.Invoice"/>
</EntityContainer>
</Schema>
</edmx:DataServices>
The SAPUI5 Web IDE says that edmx namespace does not exist.
So I went to check edmx namespace and it does not exists.
Chrome developer tools reports the same error:
Could this be the problem?
I checked and mockserver.init() is triggered.
Did Microsoft moved this namespace somewhere? Cause I was not able to find it.
Thanks
what I see is that you messed up your XML structure. As the error says your XML is invalid.
You've closed the surrounding edmx:Edmx tag at the beginning of the document
You've closed the edmx:DataServices tag too early
Furthermore the attribute name of the property id is in lowercase. Try to make an uppercased Name.
Try to use this xml:
<edmx:Edmx Version="1.0" xmlns:edmx="http://schemas.microsoft.com/ado/2007/06/edmx">
<edmx:DataServices m:DataServiceVersion="1.0" m:MaxDataServiceVersion="3.0"
xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
<Schema Namespace="PersonsData" xmlns="http://schemas.microsoft.com/ado/2008/09/edm">
<EntityType Name="Person">
<Key>
<PropertyRef Name="id"/>
</Key>
<Property Name="id" Type="Edm.Int16" Nullable="false"/>
<Property Name="first_name" Type="Edm.String" Nullable="false" MaxLength="40" FixedLength="false" Unicode="true"/>
<Property Name="last_name" Type="Edm.String" Nullable="false" MaxLength="40" FixedLength="false" Unicode="true"/>
<Property Name="email" Type="Edm.String" Nullable="false"/>
<Property Name="gender" Type="Edm.String" Nullable="false" MaxLength="40" FixedLength="false"/>
<Property Name="ip_address" Type="Edm.String" Nullable="false" MaxLength="40" FixedLength="false" Unicode="true"/>
</EntityType>
</Schema>
<Schema Namespace="databinding.PersonsData.Model" xmlns="http://schemas.microsoft.com/ado/2008/09/edm">
<EntityContainer Name="PersonEntities" m:IsDefaultEntityContainer="true" p6:LazyLoadingEnabled="true"
xmlns:p6="http://schemas.microsoft.com/ado/2009/02/edm/annotation">
<EntitySet Name="Persons" EntityType="PersonsData.Invoice"/>
</EntityContainer>
</Schema>
</edmx:DataServices>

Issue in EF, mapping fragment,no default value and is not nullable

I am developing MVC 3 Applicaiton.
I have Model first approch.
I have Company Entity(Abstract).
Lead and Customer is inherited from the company entity.
When I tried to validate the model, Its gives an errror.
Error 41 Error 3023: Problem in mapping fragments starting at line
70:Column Companies.Status in table Companies must be mapped: It has
no default value and is not nullable.
Here is the mapping of tables.
And Here is the EDMX code in HTML View.
<?xml version="1.0" encoding="utf-8"?>
<edmx:Edmx Version="2.0" xmlns:edmx="http://schemas.microsoft.com/ado/2008/10/edmx">
<!-- EF Runtime content -->
<edmx:Runtime>
<!-- SSDL content -->
<edmx:StorageModels>
<Schema Namespace="Model1.Store" Alias="Self" Provider="System.Data.SqlClient" ProviderManifestToken="2008" xmlns="http://schemas.microsoft.com/ado/2009/02/edm/ssdl" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator">
<EntityContainer Name="Model1StoreContainer">
<EntitySet Name="Companies" EntityType="Model1.Store.Companies" store:Type="Tables" Schema="dbo" />
</EntityContainer>
<EntityType Name="Companies">
<Key>
<PropertyRef Name="Id" />
</Key>
<Property Name="Id" Type="int" StoreGeneratedPattern="Identity" Nullable="false" />
<Property Name="Name" Type="nvarchar(max)" Nullable="false" />
<Property Name="Status" Type="nvarchar(max)" Nullable="false" />
<Property Name="__Disc__" Type="nvarchar" MaxLength="Max" Nullable="false" />
</EntityType>
</Schema></edmx:StorageModels>
<!-- CSDL content -->
<edmx:ConceptualModels>
<Schema xmlns="http://schemas.microsoft.com/ado/2008/09/edm" xmlns:cg="http://schemas.microsoft.com/ado/2006/04/codegeneration" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" Namespace="Model1" Alias="Self" xmlns:annotation="http://schemas.microsoft.com/ado/2009/02/edm/annotation">
<EntityContainer Name="Model1Container" annotation:LazyLoadingEnabled="true">
<EntitySet Name="Companies" EntityType="Model1.Company" />
</EntityContainer>
<EntityType Name="Company" Abstract="true">
<Key>
<PropertyRef Name="Id" />
</Key>
<Property Type="Int32" Name="Id" Nullable="false" annotation:StoreGeneratedPattern="Identity" />
<Property Type="String" Name="Name" Nullable="false" />
</EntityType>
<EntityType Name="Lead" BaseType="Model1.Company" >
<Property Type="String" Name="Status" Nullable="false" />
</EntityType>
</Schema>
</edmx:ConceptualModels>
<!-- C-S mapping content -->
<edmx:Mappings>
<Mapping Space="C-S" xmlns="http://schemas.microsoft.com/ado/2008/09/mapping/cs">
<EntityContainerMapping StorageEntityContainer="Model1StoreContainer" CdmEntityContainer="Model1Container">
<EntitySetMapping Name="Companies">
<EntityTypeMapping TypeName="IsTypeOf(Model1.Company)">
<MappingFragment StoreEntitySet="Companies">
<ScalarProperty Name="Id" ColumnName="Id" />
<ScalarProperty Name="Name" ColumnName="Name" />
<Condition ColumnName="__Disc__" Value="Company" />
</MappingFragment>
</EntityTypeMapping>
<EntityTypeMapping TypeName="Model1.Lead">
<MappingFragment StoreEntitySet="Companies">
<ScalarProperty Name="Id" ColumnName="Id" />
<ScalarProperty Name="Name" ColumnName="Name" />
<ScalarProperty Name="Status" ColumnName="Status" />
<Condition ColumnName="__Disc__" Value="Lead" />
</MappingFragment>
</EntityTypeMapping>
</EntitySetMapping>
</EntityContainerMapping>
</Mapping></edmx:Mappings>
</edmx:Runtime>
<!-- EF Designer content (DO NOT EDIT MANUALLY BELOW HERE) -->
<edmx:Designer xmlns="http://schemas.microsoft.com/ado/2008/10/edmx">
<edmx:Connection>
<DesignerInfoPropertySet>
<DesignerProperty Name="MetadataArtifactProcessing" Value="EmbedInOutputAssembly" />
</DesignerInfoPropertySet>
</edmx:Connection>
<edmx:Options>
<DesignerInfoPropertySet>
<DesignerProperty Name="ValidateOnBuild" Value="true" />
<DesignerProperty Name="EnablePluralization" Value="True" />
<DesignerProperty Name="DatabaseGenerationWorkflow" Value="$(VSEFTools)\DBGen\Generate T-SQL Via T4 (TPH).xaml" />
</DesignerInfoPropertySet>
</edmx:Options>
<!-- Diagram content (shape and connector positions) -->
<edmx:Diagrams>
<Diagram Name="Model1" >
<EntityTypeShape EntityType="Model1.Company" Width="1.5" PointX="2.375" PointY="0.875" Height="1.2636116536458335" />
<EntityTypeShape EntityType="Model1.Lead" Width="1.5" PointX="3.375" PointY="2.625" Height="1.0992643229166665" />
<InheritanceConnector EntityType="Model1.Lead" >
<ConnectorPoint PointX="3.125" PointY="2.1386116536458335" />
<ConnectorPoint PointX="3.125" PointY="2.325" />
<ConnectorPoint PointX="4.125" PointY="2.325" />
<ConnectorPoint PointX="4.125" PointY="2.625" />
</InheritanceConnector>
</Diagram>
</edmx:Diagrams>
</edmx:Designer>
</edmx:Edmx>
Whats is the issue ?
Put the DefaultValue attribute on the SSDL Status property. It would look like this (I used the empty string):
<Property Name="Status" Type="nvarchar(max)" Nullable="false" DefaultValue=""/>
Since the base entity is abstract you won't be able to create entities of this type so this DefaultValue will not really be used but it should make EF stop complaining.
In your storage model, the Companies.Status column doesn't allow null values.
Since all entities that inherit from Company except the Lead entity will not have the Status property set, you need to either allow null in the Companies.Status column or set a default value to use for the other entities.

Join two related tables into a single entity using Entity Framework

My question relates to the "table joining" function in the ADO.NET Entity Framework.
Imagine a database that contains a table "Product" and another table "ProductPrice". The price table stores a history of all price changes for a product, with a start and end date, where the line containing the current price is indicated by a NULL value in the end date column. This database structure could be useful for statistical purposes, for example the average daily sales volume could be mapped to each change in the product price. However, for the online ordering website, only the current price is required.
Here's the structure of the two tables:
Product
ProductID (PK, int, NOT NULL, auto increment)
Name (varchar 50, NOT NULL)
ProductPrice
ProductPriceID (PK, int, NOT NULL, auto increment)
ProductID (INT, NOT NULL)
StartDate (DATETIME, NOT NULL)
EndDate (DATETIME)
Price (MONEY, NOT NULL)
Here's an example of an SQL statement to retrieve the product plus the current price:
SELECT Product.ProductID, Product.Name, ProductPrice.Price AS CurrentPrice
FROM Product
LEFT JOIN ProductPrice
ON Product.ProductID = ProductPrice.ProductID
AND ProductPrice.EndDate IS NULL
I'd like to use the Entity Framework to join the entities Product and ProductPrice together, so that I can access the current price directly from the Product entity, as in the following example:
var product = (from p in context.Product where p.ProductID == 2 select p).FirstOrDefault();
Console.WriteLine(product.Name);
Console.WriteLine(product.CurrentPrice);
Unfortunately, I'm getting stuck with errors that I can't resolve.
Here are the entities from the storage model:
<EntityType Name="Product">
<Key>
<PropertyRef Name="ProductID" />
</Key>
<Property Name="ProductID" Type="int" Nullable="false" StoreGeneratedPattern="Identity" />
<Property Name="Name" Type="varchar" Nullable="false" MaxLength="50" />
</EntityType>
<EntityType Name="ProductPrice">
<Key>
<PropertyRef Name="ProductPriceID" />
</Key>
<Property Name="ProductPriceID" Type="int" Nullable="false" StoreGeneratedPattern="Identity" />
<Property Name="ProductID" Type="int" Nullable="false" />
<Property Name="Price" Type="money" Nullable="false" />
<Property Name="StartDate" Type="datetime" Nullable="false" />
<Property Name="EndDate" Type="datetime" />
</EntityType>
<Association Name="FK_ProductPrice_Product">
<End Role="Product" Type="TestingModel.Store.Product" Multiplicity="1" />
<End Role="ProductPrice" Type="TestingModel.Store.ProductPrice" Multiplicity="*" />
<ReferentialConstraint>
<Principal Role="Product">
<PropertyRef Name="ProductID" />
</Principal>
<Dependent Role="ProductPrice">
<PropertyRef Name="ProductID" />
</Dependent>
</ReferentialConstraint>
</Association>
And from the conceptual model:
<EntityType Name="Product">
<Key>
<PropertyRef Name="ProductID" />
</Key>
<Property Name="ProductID" Type="Int32" Nullable="false" annotation:StoreGeneratedPattern="Identity" />
<Property Name="Name" Type="String" Nullable="false" MaxLength="50" Unicode="false" FixedLength="false" />
<Property Name="SKU" Type="String" Nullable="false" MaxLength="50" Unicode="false" FixedLength="false" />
<Property Type="Decimal" Name="CurrentPrice" Nullable="false" Precision="19" Scale="4" />
</EntityType>
And finally the mapping between the two:
<EntitySetMapping Name="Product">
<EntityTypeMapping TypeName="TestingModel.Product">
<MappingFragment StoreEntitySet="Product">
<ScalarProperty Name="ProductID" ColumnName="ProductID" />
<ScalarProperty Name="Name" ColumnName="Name" />
<ScalarProperty Name="SKU" ColumnName="SKU" />
</MappingFragment>
</EntityTypeMapping>
<EntityTypeMapping TypeName="IsTypeOf(TestingModel.Product)">
<MappingFragment StoreEntitySet="ProductPrice">
<ScalarProperty Name="CurrentPrice" ColumnName="Price" />
<Condition ColumnName="EndDate" IsNull="true" />
</MappingFragment>
</EntityTypeMapping>
</EntitySetMapping>
And here are the error messages that I'm currently struggling with:
Error 1 Error 3024: Problem in mapping fragments starting at line 76:Must specify mapping for all key properties (Product.ProductID) of the EntitySet Product.
Error 2 Error 3025: Problem in mapping fragments starting at line 76:Must specify mapping for all key properties (ProductPrice.ProductPriceID) of table ProductPrice.
I'm not sure if this is even possible with the Entity Framework, maybe I should just do the join manually myself in LINQ.
Any suggestions would be greatly appreciated.
You do not meet the conditions for entity splitting:
You should only map an entity type to multiple tables if the following conditions are true:
The tables to which you are mapping share a common key.
The entity type that is being mapped has entries in each underlying table. In other words, the entity type represents data that has a one-to-one correspondence between the two tables; the entity type represents an inner join of the two tables.
You are smarter than EF. You know that the condition EndDate == null yields one record. EF has no clue to know that and thus never knows that it can create one object from the two tables. In terms of the exception message: PriceId and EndDate == null should somehow deliver all key properties of your ProductPrice records, which is impossible, obviously.
Alternatives:
A. You can create a one-to-many association between the two and query:
products.Where(p => p.ProductId == 2)
.Select(p => new
{
Product = p,
CurrentPrice = p.ProductPrices.Where(pp => pp.EndDate == null)
.FirstOrDefault()
})
Not as convenient as you'd like, but maybe not too bad when wrapped in a repository.
B. Create a database view and use separate paths for viewing and updating (which is not an uncommon thing to do).
You need to do a foreign key between the two tables (i.e. on column ProductID)
Then to retrieve all the products together with their prices you need to do the following:
var x = from p in context.Product where p.ProductID == 2 && p.ProductPrice.EndDate == null select new { p.ProductID, p.Name, p.ProductPrice.Price }.FirstOrDefault();

EF4 POCO (not using T4): Mapping and metadata information could not be found for EntityType

I have a pretty simple console project with an entity model (containing two simple entities), two handmade POCOs and a handmade Context class. The program fires a simple query against the DB and everything including LazyLoading works fine.
The problem: As soon as i add another Entity data model (even if i add an empty one), the calls to CreateObjectSet in Ef2PlaygroundModel_3Container throw the following exception:
Unhandled Exception: System.InvalidOperationException: Mapping and metadata information could not be found for EntityType 'EF2_Playground.Driver'.
at System.Data.Objects.ObjectContext.GetTypeUsage(Type entityCLRType)
at System.Data.Objects.ObjectContext.GetEntitySetFromContainer(EntityContainer container, Type entityCLRType, String exceptionParameterName)
at System.Data.Objects.ObjectContext.GetEntitySetForType(Type entityCLRType, String exceptionParameterName)
at System.Data.Objects.ObjectContext.CreateObjectSet[TEntity]()
at EF2_Playground.Ef2PlaygroundModel_3Container.get_Drivers() in C:\...\Ef2PlaygroundModel_3Pocos.cs:line 64
at EF2_Playground.Program.Main(String[] args) in C:\...\Program.cs:line 15
Does anyone have an idea about what is going wrong here?
That is the working project:
Ef2PlaygroundModel_3.edmx:
Code Generation Strategy is set to "None"
<?xml version="1.0" encoding="utf-8"?>
<edmx:Edmx Version="2.0" xmlns:edmx="http://schemas.microsoft.com/ado/2008/10/edmx">
<!-- EF Runtime content -->
<edmx:Runtime>
<!-- SSDL content -->
<edmx:StorageModels>
<Schema Namespace="Ef2PlaygroundModel_3.Store" Alias="Self" Provider="System.Data.SqlClient" ProviderManifestToken="2008" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" xmlns="http://schemas.microsoft.com/ado/2009/02/edm/ssdl">
<EntityContainer Name="Ef2PlaygroundModel_3StoreContainer">
<EntitySet Name="Cars" EntityType="Ef2PlaygroundModel_3.Store.Cars" store:Type="Tables" Schema="dbo"/>
<EntitySet Name="Drivers" EntityType="Ef2PlaygroundModel_3.Store.Drivers" store:Type="Tables" Schema="dbo"/>
<EntitySet Name="CarDriver" EntityType="Ef2PlaygroundModel_3.Store.CarDriver" store:Type="Tables" Schema="dbo"/>
<AssociationSet Name="FK_CarDriver_Car" Association="Ef2PlaygroundModel_3.Store.FK_CarDriver_Car">
<End Role="Car" EntitySet="Cars"/>
<End Role="CarDriver" EntitySet="CarDriver"/>
</AssociationSet>
<AssociationSet Name="FK_CarDriver_Driver" Association="Ef2PlaygroundModel_3.Store.FK_CarDriver_Driver">
<End Role="Driver" EntitySet="Drivers"/>
<End Role="CarDriver" EntitySet="CarDriver"/>
</AssociationSet>
</EntityContainer>
<EntityType Name="Cars">
<Key>
<PropertyRef Name="Id"/>
</Key>
<Property Name="Id" Type="int" StoreGeneratedPattern="Identity" Nullable="false"/>
<Property Name="Brand" Type="nvarchar(max)" Nullable="false"/>
<Property Name="Model" Type="nvarchar(max)" Nullable="false"/>
<Property Name="ReleaseDate" Type="datetime" Nullable="true"/>
</EntityType>
<EntityType Name="Drivers">
<Key>
<PropertyRef Name="Id"/>
</Key>
<Property Name="Id" Type="int" StoreGeneratedPattern="Identity" Nullable="false"/>
<Property Name="Name" Type="nvarchar(max)" Nullable="false"/>
</EntityType>
<EntityType Name="CarDriver">
<Key>
<PropertyRef Name="Cars_Id"/>
<PropertyRef Name="Drivers_Id"/>
</Key>
<Property Name="Cars_Id" Type="int" Nullable="false"/>
<Property Name="Drivers_Id" Type="int" Nullable="false"/>
</EntityType>
<Association Name="FK_CarDriver_Car">
<End Role="Car" Type="Ef2PlaygroundModel_3.Store.Cars" Multiplicity="1"/>
<End Role="CarDriver" Type="Ef2PlaygroundModel_3.Store.CarDriver" Multiplicity="*"/>
<ReferentialConstraint>
<Principal Role="Car">
<PropertyRef Name="Id"/>
</Principal>
<Dependent Role="CarDriver">
<PropertyRef Name="Cars_Id"/>
</Dependent>
</ReferentialConstraint>
</Association>
<Association Name="FK_CarDriver_Driver">
<End Role="CarDriver" Type="Ef2PlaygroundModel_3.Store.CarDriver" Multiplicity="*"/>
<End Role="Driver" Type="Ef2PlaygroundModel_3.Store.Drivers" Multiplicity="1"/>
<ReferentialConstraint>
<Principal Role="Driver">
<PropertyRef Name="Id"/>
</Principal>
<Dependent Role="CarDriver">
<PropertyRef Name="Drivers_Id"/>
</Dependent>
</ReferentialConstraint>
</Association>
</Schema>
</edmx:StorageModels>
<!-- CSDL content -->
<edmx:ConceptualModels>
<Schema xmlns="http://schemas.microsoft.com/ado/2008/09/edm" xmlns:cg="http://schemas.microsoft.com/ado/2006/04/codegeneration" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" Namespace="Ef2PlaygroundModel_3" Alias="Self" xmlns:annotation="http://schemas.microsoft.com/ado/2009/02/edm/annotation">
<EntityContainer Name="Ef2PlaygroundModel_3Container" annotation:LazyLoadingEnabled="true">
<EntitySet Name="Cars" EntityType="Ef2PlaygroundModel_3.Car"/>
<EntitySet Name="Drivers" EntityType="Ef2PlaygroundModel_3.Driver"/>
<AssociationSet Name="CarDriver" Association="Ef2PlaygroundModel_3.CarDriver">
<End Role="Car" EntitySet="Cars"/>
<End Role="Driver" EntitySet="Drivers"/>
</AssociationSet>
</EntityContainer>
<EntityType Name="Car">
<Key>
<PropertyRef Name="Id"/>
</Key>
<Property Type="Int32" Name="Id" Nullable="false" annotation:StoreGeneratedPattern="Identity"/>
<Property Type="String" Name="Brand" Nullable="false"/>
<Property Type="String" Name="Model" Nullable="false"/>
<Property Type="DateTime" Name="ReleaseDate" Nullable="true"/>
<NavigationProperty Name="Drivers" Relationship="Ef2PlaygroundModel_3.CarDriver" FromRole="Car" ToRole="Driver"/>
</EntityType>
<EntityType Name="Driver">
<Key>
<PropertyRef Name="Id"/>
</Key>
<Property Type="Int32" Name="Id" Nullable="false" annotation:StoreGeneratedPattern="Identity"/>
<Property Type="String" Name="Name" Nullable="false"/>
<NavigationProperty Name="Cars" Relationship="Ef2PlaygroundModel_3.CarDriver" FromRole="Driver" ToRole="Car"/>
</EntityType>
<Association Name="CarDriver">
<End Type="Ef2PlaygroundModel_3.Car" Role="Car" Multiplicity="*"/>
<End Type="Ef2PlaygroundModel_3.Driver" Role="Driver" Multiplicity="*"/>
</Association>
</Schema>
</edmx:ConceptualModels>
<!-- C-S mapping content -->
<edmx:Mappings>
<Mapping Space="C-S" xmlns="http://schemas.microsoft.com/ado/2008/09/mapping/cs">
<EntityContainerMapping StorageEntityContainer="Ef2PlaygroundModel_3StoreContainer" CdmEntityContainer="Ef2PlaygroundModel_3Container">
<EntitySetMapping Name="Cars">
<EntityTypeMapping TypeName="IsTypeOf(Ef2PlaygroundModel_3.Car)">
<MappingFragment StoreEntitySet="Cars">
<ScalarProperty Name="Id" ColumnName="Id"/>
<ScalarProperty Name="Brand" ColumnName="Brand"/>
<ScalarProperty Name="Model" ColumnName="Model"/>
<ScalarProperty Name="ReleaseDate" ColumnName="ReleaseDate"/>
</MappingFragment>
</EntityTypeMapping>
</EntitySetMapping>
<EntitySetMapping Name="Drivers">
<EntityTypeMapping TypeName="IsTypeOf(Ef2PlaygroundModel_3.Driver)">
<MappingFragment StoreEntitySet="Drivers">
<ScalarProperty Name="Id" ColumnName="Id"/>
<ScalarProperty Name="Name" ColumnName="Name"/>
</MappingFragment>
</EntityTypeMapping>
</EntitySetMapping>
<AssociationSetMapping Name="CarDriver" TypeName="Ef2PlaygroundModel_3.CarDriver" StoreEntitySet="CarDriver">
<EndProperty Name="Car">
<ScalarProperty Name="Id" ColumnName="Cars_Id"/>
</EndProperty>
<EndProperty Name="Driver">
<ScalarProperty Name="Id" ColumnName="Drivers_Id"/>
</EndProperty>
</AssociationSetMapping>
</EntityContainerMapping>
</Mapping>
</edmx:Mappings>
</edmx:Runtime>
<!-- EF Designer content (DO NOT EDIT MANUALLY BELOW HERE) -->
<edmx:Designer xmlns="http://schemas.microsoft.com/ado/2008/10/edmx">
<edmx:Connection>
<DesignerInfoPropertySet>
<DesignerProperty Name="MetadataArtifactProcessing" Value="EmbedInOutputAssembly"/>
</DesignerInfoPropertySet>
</edmx:Connection>
<edmx:Options>
<DesignerInfoPropertySet>
<DesignerProperty Name="ValidateOnBuild" Value="true"/>
<DesignerProperty Name="EnablePluralization" Value="False"/>
<DesignerProperty Name="CodeGenerationStrategy" Value="None"/>
</DesignerInfoPropertySet>
</edmx:Options>
<!-- Diagram content (shape and connector positions) -->
<edmx:Diagrams>
<Diagram Name="Ef2PlaygroundModel_3">
<EntityTypeShape EntityType="Ef2PlaygroundModel_3.Car" Width="1.5" PointX="3.25" PointY="1.625" Height="1.787985026041667"/>
<EntityTypeShape EntityType="Ef2PlaygroundModel_3.Driver" Width="1.5" PointX="5.375" PointY="1.625" Height="1.59568359375"/>
<AssociationConnector Association="Ef2PlaygroundModel_3.CarDriver">
<ConnectorPoint PointX="4.75" PointY="2.422841796875"/>
<ConnectorPoint PointX="5.375" PointY="2.422841796875"/>
</AssociationConnector>
</Diagram>
</edmx:Diagrams>
</edmx:Designer>
</edmx:Edmx>
app.config:
<configuration>
<connectionStrings>
<add
name="Ef2PlaygroundModel_3Container"
connectionString="metadata=res://*/Ef2PlaygroundModel_3.csdl|res://*/Ef2PlaygroundModel_3.ssdl|res://*/Ef2PlaygroundModel_3.msl;provider=System.Data.SqlClient;provider connection string="Data Source=.\SqlExpress;Initial Catalog=Ef2PlaygroundModel_3;Integrated Security=True;MultipleActiveResultSets=True""
providerName="System.Data.EntityClient"
/>
</connectionStrings>
</configuration>
Ef2PlaygroundModel_3Pocos.cs:
using System;
using System.Collections.Generic;
using System.Data.Objects;
namespace EF2_Playground
{
public class Car
{
public Car()
{
Drivers = new List<Driver>();
}
public int Id { get; set; }
public string Brand { get; set; }
public string Model { get; set; }
public DateTime? ReleaseDate { get; set; }
public virtual List<Driver> Drivers { get; private set; }
}
public class Driver
{
public Driver()
{
Cars = new List<Car>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual List<Car> Cars { get; private set; }
}
public class Ef2PlaygroundModel_3Container : ObjectContext
{
public Ef2PlaygroundModel_3Container()
: base("name=Ef2PlaygroundModel_3Container")
{
ContextOptions.LazyLoadingEnabled = true;
}
public IObjectSet<Car> Cars
{
get { return CreateObjectSet<Car>(); }
}
public IObjectSet<Driver> Drivers
{
get { return CreateObjectSet<Driver>(); }
}
}
}
Program.cs:
using System;
namespace EF2_Playground
{
class Program
{
static void Main(string[] args)
{
using (var ctx = new Ef2PlaygroundModel_3Container())
{
foreach (var driver in ctx.Drivers)
{
Console.WriteLine(driver.Name);
foreach (var car in driver.Cars)
{
Console.WriteLine(" drives a {0} - {1} (released on {2})", car.Brand, car.Model, car.ReleaseDate);
}
}
}
}
}
}
And finally Model1.edmx that breaks the whole thing as soon as i add it to the project:
<?xml version="1.0" encoding="utf-8"?>
<edmx:Edmx Version="2.0" xmlns:edmx="http://schemas.microsoft.com/ado/2008/10/edmx">
<!-- EF Runtime content -->
<edmx:Runtime>
<!-- SSDL content -->
<edmx:StorageModels>
<Schema xmlns="http://schemas.microsoft.com/ado/2009/02/edm/ssdl" Namespace="Model1.Store" Alias="Self" Provider="System.Data.SqlClient" ProviderManifestToken="2005">
<EntityContainer Name="Model1TargetContainer">
</EntityContainer>
</Schema>
</edmx:StorageModels>
<!-- CSDL content -->
<edmx:ConceptualModels>
<Schema xmlns="http://schemas.microsoft.com/ado/2008/09/edm" xmlns:cg="http://schemas.microsoft.com/ado/2006/04/codegeneration" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" Namespace="Model1" Alias="Self" xmlns:annotation="http://schemas.microsoft.com/ado/2009/02/edm/annotation">
<EntityContainer Name="Model1Container" annotation:LazyLoadingEnabled="true">
</EntityContainer>
</Schema>
</edmx:ConceptualModels>
<!-- C-S mapping content -->
<edmx:Mappings>
<Mapping xmlns="http://schemas.microsoft.com/ado/2008/09/mapping/cs" Space="C-S">
<Alias Key="Model" Value="Model1"/>
<Alias Key="Target" Value="Model1.Store"/>
<EntityContainerMapping CdmEntityContainer="Model1Container" StorageEntityContainer="Model1TargetContainer">
</EntityContainerMapping>
</Mapping>
</edmx:Mappings>
</edmx:Runtime>
<!-- EF Designer content (DO NOT EDIT MANUALLY BELOW HERE) -->
<edmx:Designer xmlns="http://schemas.microsoft.com/ado/2008/10/edmx">
<edmx:Connection>
<DesignerInfoPropertySet>
<DesignerProperty Name="MetadataArtifactProcessing" Value="EmbedInOutputAssembly"/>
</DesignerInfoPropertySet>
</edmx:Connection>
<edmx:Options>
<DesignerInfoPropertySet>
<DesignerProperty Name="ValidateOnBuild" Value="true"/>
<DesignerProperty Name="EnablePluralization" Value="False"/>
</DesignerInfoPropertySet>
</edmx:Options>
<!-- Diagram content (shape and connector positions) -->
<edmx:Diagrams>
<Diagram Name="Model1"/>
</edmx:Diagrams>
</edmx:Designer>
</edmx:Edmx>
Ok, i guess i've got it. I reduced the second model (the one that brakes the project) to the following:
Class1.cs
using System.Data.Objects.DataClasses;
[assembly: EdmSchemaAttribute()]
Bang! The well known exception appears.
As in so many cases, reading the documentation helps:
Mapping POCO entities is not supported if any mapping attributes are applied to custom data classes, including EdmSchemaAttribute at the assembly level.
Sure, i do not literally add mapping attributes to CUSTOM data classes but that doesn't matter for the EdmSchemaAttribute since that one lives on the assembly level.
Adding the second non-POCO model causes code generation resulting in a class that contains (at least) the EdmSchemaAttribute and that is not supported.
What i've learned: Don't mix POCO and non-POCO models in one assembly.
My guess is that ef is lookig at the wrong model. Is there any chance that the models are using the same namespace? You can modify the CSDLs namespace in the property window. What happens if you modify the csdl namespace of the new, empty model?
In the properties of your *.edmx if you are using POCO, then you should set the CodeGenerationStrategy to none.

Entity Framework TPH with multiple abstract inheritance

I'm trying to do a Table Per Hierarchy model in Entity Framework(VS 2008 sp1, 3.5).
Most of my models have been very simple, an abstract type with multiple sub-types that inherit from it.
However, I've been struggling with this latest challenge. I have STUDENTS that I'd like to inherit from PERSONS(abstract) that should inherity from PARTIES(abstract).
Every time I do this I get a "Error 2078: The EntityType 'Model.PERSONS' is Abstract and can be mapped only using IsTypeOf." I guess the problem is PARTIES is already defined as IsTypeOf in the entity set.
So is this even possible? I can work around it by making PERSONS abstract = false and assigning a bogus conditional mapping. But this seems like a silly workaround.
Edit the model using XML Editor: find the mapping and add IsTypeOf to the corresponding EntityTypeMapping tag.
Here is an example resembling your case:
SQL Server DDL:
CREATE TABLE [dbo].[Student] (
[Id] [int] IDENTITY(1,1) NOT NULL,
[PartyInfo] [varchar](max) NOT NULL,
[PersonInfo] [varchar](max) NOT NULL,
[StudInfo] [varchar](max) NOT NULL,
CONSTRAINT [PK_Student] PRIMARY KEY CLUSTERED ( [Id] ASC )
)
EDMX:
<?xml version="1.0" encoding="utf-8"?>
<edmx:Edmx Version="1.0"
xmlns:edmx="http://schemas.microsoft.com/ado/2007/06/edmx">
<!-- EF Runtime content -->
<edmx:Runtime>
<!-- SSDL content -->
<edmx:StorageModels>
<Schema Namespace="test_1Model.Store" Alias="Self"
Provider="System.Data.SqlClient" ProviderManifestToken="2005"
xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator"
xmlns="http://schemas.microsoft.com/ado/2006/04/edm/ssdl">
<EntityContainer Name="test_1ModelStoreContainer">
<EntitySet Name="Student" EntityType="test_1Model.Store.Student"
store:Type="Tables" Schema="dbo" />
</EntityContainer>
<EntityType Name="Student">
<Key>
<PropertyRef Name="Id" />
</Key>
<Property Name="Id" Type="int" Nullable="false"
StoreGeneratedPattern="Identity" />
<Property Name="PartyInfo" Type="varchar(max)" Nullable="false" />
<Property Name="PersonInfo" Type="varchar(max)" Nullable="false" />
<Property Name="StudInfo" Type="varchar(max)" Nullable="false" />
</EntityType>
</Schema>
</edmx:StorageModels>
<!-- CSDL content -->
<edmx:ConceptualModels>
<Schema Namespace="test_1Model" Alias="Self"
xmlns="http://schemas.microsoft.com/ado/2006/04/edm">
<EntityContainer Name="test_Entities">
<EntitySet Name="PartySet" EntityType="test_1Model.Party" />
</EntityContainer>
<EntityType Name="Party" Abstract="true">
<Key>
<PropertyRef Name="Id" />
</Key>
<Property Name="Id" Type="Int32" Nullable="false" />
<Property Name="PartyInfo" Type="String" Nullable="false"
MaxLength="Max" Unicode="false" FixedLength="false" />
</EntityType>
<EntityType Name="Person" BaseType="test_1Model.Party" Abstract="true" >
<Property Name="PersonInfo" Type="String" Nullable="false" />
</EntityType>
<EntityType Name="Student" BaseType="test_1Model.Person" >
<Property Name="StudInfo" Type="String" Nullable="false" />
</EntityType>
</Schema>
</edmx:ConceptualModels>
<!-- C-S mapping content -->
<edmx:Mappings>
<Mapping Space="C-S"
xmlns="urn:schemas-microsoft-com:windows:storage:mapping:CS">
<EntityContainerMapping
StorageEntityContainer="test_1ModelStoreContainer"
CdmEntityContainer="test_Entities">
<EntitySetMapping Name="PartySet">
<EntityTypeMapping TypeName="IsTypeOf(test_1Model.Party)">
<MappingFragment StoreEntitySet="Student">
<ScalarProperty Name="PartyInfo" ColumnName="PartyInfo" />
<ScalarProperty Name="Id" ColumnName="Id" />
</MappingFragment>
</EntityTypeMapping>
<EntityTypeMapping TypeName="IsTypeOf(test_1Model.Person)">
<MappingFragment StoreEntitySet="Student">
<ScalarProperty Name="Id" ColumnName="Id" />
<ScalarProperty Name="PersonInfo" ColumnName="PersonInfo" />
</MappingFragment>
</EntityTypeMapping>
<EntityTypeMapping TypeName="test_1Model.Student">
<MappingFragment StoreEntitySet="Student">
<ScalarProperty Name="PartyInfo" ColumnName="PartyInfo" />
<ScalarProperty Name="PersonInfo" ColumnName="PersonInfo" />
<ScalarProperty Name="Id" ColumnName="Id" />
<ScalarProperty Name="StudInfo" ColumnName="StudInfo" />
</MappingFragment>
</EntityTypeMapping>
</EntitySetMapping>
</EntityContainerMapping>
</Mapping>
</edmx:Mappings>
</edmx:Runtime>
<!-- EF Designer content (DO NOT EDIT MANUALLY BELOW HERE) -->
<edmx:Designer xmlns="http://schemas.microsoft.com/ado/2007/06/edmx">
<edmx:Connection>
<DesignerInfoPropertySet>
<DesignerProperty Name="MetadataArtifactProcessing"
Value="EmbedInOutputAssembly" />
</DesignerInfoPropertySet>
</edmx:Connection>
<edmx:Options>
<DesignerInfoPropertySet>
<DesignerProperty Name="ValidateOnBuild" Value="true" />
</DesignerInfoPropertySet>
</edmx:Options>
<!-- Diagram content (shape and connector positions) -->
<edmx:Diagrams>
<Diagram Name="SqlServer_Model" />
</edmx:Diagrams>
</edmx:Designer>
</edmx:Edmx>