I have 2 tables: Data and AdditionalData. Their relation is 1 to 1-0 (any Data can have 0 or 1 AdditionalData).
For main context I have classes:
class Data
{
public long Id {get;set;} // PK
public string Name {get;set;}
public AdditionalData AdditionalData {get;set;} // can be null
}
class AdditionalData
{
public long Id {get;set;} // PK
public string AdditionalName {get;set;}
}
This works fine.
For another context I just need to know, whether Data has AdditionalData or not:
class ExtendedData
{
public long Id {get;set;} //PK
public string Name {get;set;}
public bool HasAdditionalData {get;set;}
}
I can map it to view:
SELECT
d.*
,IIF(ad.Id IS NULL, 0, 1) AS HasAdditionalData
FROM Data AS d
LEFT OUTER JOIN AdditionalData AS ad ON d.Id = ad.Id
But I want to know:
Can I map ExtendedData class to tables without additional view?
A query like the one below might be what you are looking for, if you are ok with just using ExtendedData as the result of a projection:
var result = ctx.Data.Select(d => new ExtendedData {Id = d.Id, Name = d.Name, HasAdditionalData = d.ApprovalStatus != null);
The problem is that your PK is playing double duty as FK also, had you defined the FK for AdditionalData as another field, nullable AdditionalDataId perhaps, then checking for the existence of AdditionalData would be trivial; just check if AdditionalDataId is null, and you would get better performance also.
You could avoid creation of database view with DefiningQuery construct. DefiningQuery provides the same functionality as database view, but it's defined in your model, not in the database itself.
You can't create DefiningQuery with Visual Studio Model Designer though, you should manually edit your edmx file. At first add EntityType and EntitySet definitions to SSDL layer:
<!-- SSDL content -->
<edmx:StorageModels>
<Schema Namespace="TestDataModel.Store" Provider="System.Data.SqlClient" ProviderManifestToken="2012" Alias="Self" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" xmlns:customannotation="http://schemas.microsoft.com/ado/2013/11/edm/customannotation" xmlns="http://schemas.microsoft.com/ado/2009/11/edm/ssdl">
<EntityType Name="ExtendedData">
<Key>
<PropertyRef Name="Id" />
</Key>
<Property Name="Id" Type="bigint" Nullable="false" StoreGeneratedPattern="Identity" />
<Property Name="Name" Type="nvarchar(max)" Nullable="false" />
<Property Name="HasAdditionalData" Type="bit" Nullable="false" />
</EntityType>
<EntityContainer Name="TestDataModelStoreContainer">
<EntitySet Name="ExtendedData" EntityType="Self.ExtendedData" store:Type="Views" store:Schema="dbo" store:Name="ExtendedData">
<DefiningQuery>
SELECT d.Id, d.Name, CAST(IIF(ad.Id IS NULL, 0, 1) AS BIT) AS HasAdditionalData
FROM Data AS d
LEFT OUTER JOIN AdditionalData AS ad ON d.Id = ad.Id
</DefiningQuery>
</EntitySet>
</EntityContainer>
</Schema></edmx:StorageModels>
Note that your View query is specified under DefiningQuery element with slight changes.
Then you should add ExtendedData entity to CSDL. This could be done with further manual editing of edmx or with Model Designer. Here how it looks finally:
<!-- CSDL content -->
<edmx:ConceptualModels>
<Schema Namespace="TestDataModel" Alias="Self" annotation:UseStrongSpatialTypes="false" xmlns:annotation="http://schemas.microsoft.com/ado/2009/02/edm/annotation" xmlns:customannotation="http://schemas.microsoft.com/ado/2013/11/edm/customannotation" xmlns="http://schemas.microsoft.com/ado/2009/11/edm">
<EntityContainer Name="TestDataEntities2" annotation:LazyLoadingEnabled="true">
<EntitySet Name="ExtendedDatas" EntityType="TestDataModel.ExtendedData" />
</EntityContainer>
<EntityType Name="ExtendedData">
<Key>
<PropertyRef Name="Id" />
</Key>
<Property Name="Id" Type="Int64" Nullable="false" annotation:StoreGeneratedPattern="Identity" />
<Property Name="Name" Type="String" Nullable="false" />
<Property Name="HasAdditionalData" Type="Boolean" Nullable="false" />
</EntityType>
</Schema>
</edmx:ConceptualModels>
Then you should add CSDL-SSDL mapping, again manually editing edmx or through Table Mapping:
<!-- C-S mapping content -->
<edmx:Mappings>
<Mapping Space="C-S" xmlns="http://schemas.microsoft.com/ado/2009/11/mapping/cs">
<EntityContainerMapping StorageEntityContainer="TestDataModelStoreContainer" CdmEntityContainer="TestDataEntities2">
<EntitySetMapping Name="ExtendedDatas">
<EntityTypeMapping TypeName="IsTypeOf(TestDataModel.ExtendedData)">
<MappingFragment StoreEntitySet="ExtendedData">
<ScalarProperty Name="HasAdditionalData" ColumnName="HasAdditionalData" />
<ScalarProperty Name="Name" ColumnName="Name" />
<ScalarProperty Name="Id" ColumnName="Id" />
</MappingFragment>
</EntityTypeMapping>
</EntitySetMapping>
</EntityContainerMapping>
</Mapping>
</edmx:Mappings>
Be careful: Any manual changes in SSDL part of your edmx will be lost if you update your model from the database.
Related
I have this XML file:
<XtraSerializer version="1.0" application="View">
<property name="Columns" iskey="true" value="23">
<property name="Item23" isnull="true" iskey="true">
<property name="Name">colworkspace</property>
<property name="Width">75</property>
<property name="MinWidth">20</property>
<property name="MaxWidth">0</property>
</property>
</property>
<property name="FormatRules" iskey="true" value="1">
<property name="Item1" isnull="true" iskey="true">
<property name="ColumnName">colid</property>
<property name="Name">Format0</property>
<property name="RuleType">#FormatConditionRuleExpression</property>
<property name="Rule" isnull="true" iskey="true">
<property name="Expression">[id] > 1L</property>
<property name="Appearance" isnull="true" iskey="true">
<property name="Options" isnull="true" iskey="true">
<property name="UseForeColor">true</property>
</property>
<property name="ForeColor">195, 214, 155</property>
</property>
</property>
</property>
</property>
</XtraSerializer>
It has two properties, Columns and FormatRules. I want to delete the Columns property and keep the FormatRules property. What I have done is creating a method that deletes all elements which does not have name = FormatRules but that will delete all the children of the FormatRules property too, which I don't want. This is my code:
XDocument doc = XDocument.Load(path);
IEnumerable<XElement> element = from node in doc.Descendants("property")
let attr = node.Attribute("name")
where attr != null && attr.Value != "FormatRules"
select node;
element.ToList().ForEach(x => x.Remove());
doc.Save(path);
This will result in this XML file:
<XtraSerializer version="1.0" application="View">
<property name="FormatRules" iskey="true" value="1">
</XtraSerializer>
//IEnumerable<XElement> element = from node in doc.Descendants("property")
IEnumerable<XElement> element = from node in doc.Root.Elements("property")
So, I included a Stored Proc in my EF ORM. I added the SP to EF by doing Import Function. I chose to create a Complex Type from the SP columns, FolderColumn. After selecting Run Custom Tool the SP was added to my entity's context cs file:
public virtual ObjectResult<FolderColumn> GetColumnFolderModel(Nullable<long> caseid, Nullable<long> folderid, Nullable<long> userid)
{
var caseidParameter = caseid.HasValue ?
new ObjectParameter("caseid", caseid) :
new ObjectParameter("caseid", typeof(long));
var folderidParameter = folderid.HasValue ?
new ObjectParameter("folderid", folderid) :
new ObjectParameter("folderid", typeof(long));
var useridParameter = userid.HasValue ?
new ObjectParameter("userid", userid) :
new ObjectParameter("userid", typeof(long));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<FolderColumn>("GetColumnFolderModel", caseidParameter, folderidParameter, useridParameter);
}
I see the entity in the Context Model:
And editing my Context.edmx with the XML editor I found:
<ComplexType Name="FolderColumn">
<Property Type="Int64" Name="id" Nullable="false" />
<Property Type="String" Name="Display" Nullable="false" MaxLength="256" />
<Property Type="String" Name="Name" Nullable="false" MaxLength="256" />
<Property Type="String" Name="Width" Nullable="true" MaxLength="12" />
<Property Type="Boolean" Name="Sortable" Nullable="true" />
<Property Type="String" Name="Align" Nullable="true" MaxLength="48" />
<Property Type="Boolean" Name="Hide" Nullable="true" />
</ComplexType>
under the <Schema> tag, along with my common Entity Types.
What I don't see is the Complex Type, FolderColumn in the Context.cs. And, more importantly, the Complex Type is not mapped to the entity, such that I cannot do:
BriefcaseEntities context = new BriefcaseEntities();
context.FolderColumn // <--- Not part of the context
and any reference to FolderColumn throws
The type or namespace name 'FolderColumn' could not be found (are you missing a using directive or an assembly reference?)
Why is my new Complex Type not part of my Context entities?
A Complex Type represents something structured, but not stored. Entities are all stored in tables; Complex Types can come back from SPs, views, etc. So it's what I'd expect to see.
I try to get some specific values from an xml config. See example below.
<?xml version="1.0" encoding="utf-8"?>
<ExcelConfig>
<ExcelDocument name="Customer" type="flat">
<IdentityColumn>
<Column name="Id" />
</IdentityColumn>
<Validate>
<Column name="Name" mandatory="true" />
<Column name="FirstName" mandatory="true" />
<OrColumns mandatory="true">
<Column name="PostalCode" mandatory="false" />
<Column name="PostalCode2" mandatory="false" />
</OrColumns>
</Validate>
</ExcelDocument>
<ExcelDocument name="Company" type="flat">
<IdentityColumn>
<Column name="Id" />
</IdentityColumn>
<Validate>
<Column name="Name" mandatory="true" />
<Column name="FirstName" mandatory="true" />
<OrColumns mandatory="true">
<Column name="PostalCode" mandatory="false" />
<Column name="PostalCode2" mandatory="false" />
</OrColumns>
</Validate>
</ExcelDocument>
<ExcelDocument name="SomeOtherType" type="block">
<IdentityBlock>
<Column name="Period" col="A" />
<Column name="Period2" col="B" />
</IdentityBlock>
<Validate>
<Column name="Name" mandatory="true" />
<Column name="FirstName" mandatory="true" />
</Validate>
</ExcelDocument>
</ExcelConfig>
I use the following code to get some information from the excel file.
"ValidationConfiguration" is the string with the previous configuration.
//Get Different NodeTypes of Excel documents
List<XPathNavigator> types = XmlHelper.GetNodeTypes(validationConfiguration, "/ExcelConfig/ExcelDocument");
List<XPathNavigator> flatTypes = XmlHelper.GetNodeTypes(validationConfiguration,
"//ExcelConfig/ExcelDocument[#type='flat']");
List<XPathNavigator> blockTypes = XmlHelper.GetNodeTypes(validationConfiguration,
"//ExcelConfig/ExcelDocument[#type='block']");
//First we check if the file is from the flat type and get the IdentityColumns
List<XPathNavigator> identityColumnsNode = XmlHelper.GetNodeTypes(validationConfiguration, "//ExcelConfig/ExcelDocument[#type='flat']/IdentityColumn");
You can find the XmlHelper class below.
public static class XmlHelper
{
public static List<XPathNavigator> GetNodeTypes(string xmlConfiguration,string xPath)
{
XPathDocument doc = new XPathDocument(new StringReader(xmlConfiguration));
XPathNavigator nav = doc.CreateNavigator();
XPathExpression expr = nav.Compile(xPath);
List<XPathNavigator> elements = new List<XPathNavigator>();
foreach (XPathNavigator node in nav.Select(expr))
{
elements.Add(node);
}
return elements;
}
public static List<string> GetIdentityColumnNames(List<XPathNavigator> xPathNavigators)
{
List<string> identityColumns = new List<string>();
foreach (XPathNavigator xPathNavigator in xPathNavigators)
{
foreach (XPathNavigator test in xPathNavigator.Select("//Column"))
{
identityColumns.Add(test.GetAttribute("name", ""));
}
}
return identityColumns;
}
}
Now i want to do the following. I selected the identityColumnsNodes(they contains the IdentityColumn from the exceldocuments that have the flat type).
The i get for al that types the colums. But when i try that, i get all columns back from the whole file. He don't only the items from the node that i use.
foreach (XPathNavigator identityColumNode in identityColumnsNode)
{
List<string> identityColumns = XmlHelper.GetIdentityColumnNames(identityColumnsNode);
}
The second problem/thing i want to do --> the best way to select the right validate node from the specific file. With the identityColumns (that i get back and my list of HeaderRow Cells i know what file it is. But how can i select that validate node?
Or are their better methods to do this stuff?
I have this code. Also here is a sample of the XML. I apologize for any confusion
<object type="node" >
<property name="id" value="1" />
<property name="name" value="ossvc06_node1" />
<property name="port_id" value="50050768014062AC" />
<property name="port_status" value="active" />
<property name="port_speed" value="4Gb" />
<property name="port_id" value="50050768013062AC" />
<property name="port_status" value="active" />
<property name="port_speed" value="4Gb" />
<property name="port_id" value="50050768011062AC" />
<property name="port_status" value="active" />
<property name="port_speed" value="4Gb" />
<property name="port_id" value="50050768012062AC" />
<property name="port_status" value="active" />
<property name="port_speed" value="4Gb" />
<property name="hardware" value="8G4" />
<property name="iscsi_name" value="iqn.1986-03.com.ibm:2145.ossvc06.ossvc06node1" />
<property name="iscsi_alias" value="" />
<property name="failover_active" value="no" />
<property name="failover_name" value="ossvc06_node2" />
<property name="failover_iscsi_name" value="iqn.1986- .com.ibm:2145.ossvc06.ossvc06node2" />
<property name="failover_iscsi_alias" value="" />
<property name="front_panel_id" value="115286" />
</object>
In the input file there are two of these objects of type "Node" each with different values for the property tags.
In this code I am looking for all the objects of type "node" in the incoming XML. There are 2 of them. The 'var nodes' statement evaluates correctly. In the debugger I can see two XElements with what appears to be the proper type and elements in the element list. However, the statement that gets the elements and assigns them to a list has ChildElements from both of the objects of type "node" that are in the XML and I am not sure why.
//load the input file
XDocument xdoc = XDocument.Load(_InputFile);
//get the object of type 'node'
//this code gives the results expected
// in the debugger each XElement appears to have the proper value and childElements
var nodes = from node in xdoc.Descendants("object")
where node.Attribute("type").Value == "node"
select node;
foreach (XElement nodelement in nodes)
{
// problem happens here, the child elements from both nodes get assigned to the list
List<XElement> nodeles = nodelement.Elements().ToList();
Node node = NodeFactory(nodelement);
// now assign the node to the correct IO group
var iogrp = SVCClusters[0].IOGroups.Where(io => io.Name == node.IOGroupName);
if (iogrp.FirstOrDefault().FirstNode == null) { iogrp.FirstOrDefault().FirstNode = node; }
else { iogrp.FirstOrDefault().SecondNode = node; }
}
Can you run this in a console app and tell me what you get
static void Main(string[] args)
{
XDocument xdoc = XDocument.Parse("<root><object type=\"node\" ><property name=\"id\" value=\"1\" /><property name=\"name\" value=\"ossvc06_node1\" /></object><object type=\"node\" ><property name=\"id\" value=\"2\" /><property name=\"name\" value=\"ossvc06_node2\" /></object></root>");
var nodes = xdoc.Descendants("object").Where(node => node.Attribute("type").Value == "node").ToList();
foreach (XElement nodelement in nodes)
{
List<XElement> nodeles = nodelement.Elements().ToList();
foreach (var node in nodeles)
Console.WriteLine(node);
}
}
You should have 4 rows output to the console
Edit---
Original issue was that an XPath expression "//property[#name='port_id']" was being used. This queries from the document root, not from the current node.
Change the XPath to be either "property[#name='port_id'] or ".//property[#name='port_id']"
I have an XML that is laid out to be reformatted into nested HTML table headers. I am working on getting each tier of the XML document into it's own list. For example:
<column name="Total" size="0">
<column name="Users" size="0" />
</column>
<column name="Date" size="0" />
<column name="Unique" size="0">
<column name="Clicks" size="0">
<column name="RC" size="0" />
<column name="CB" size="0" />
</column>
</column>
From this example, columns "Total", "Date", and "Unique" should be in the first list. Columns "Users" and "Clicks" should be in the second list. And, columns "RC" and "CB" should be in the third list. This should be accomplished using recursion to make the method completely dynamic. Any help is greatly appreciated.
Here you go:
XElement root = XElement.Parse(#"
<doc>
<column1>
<column2 />
</column1>
<column3 />
<column4>
<column5>
<column6 />
<column7 />
</column5>
</column4>
</doc>");
List<List<XElement>> outerList = new List<List<XElement>>();
List<XElement> innerList = root.Elements().ToList();
while (innerList.Any())
{
outerList.Add(innerList);
innerList = innerList.SelectMany(element => element.Elements()).ToList();
}
Edit: If you want to strip ancestor XElement instances of their descendants within your list, then you could use the following:
XElement root = XElement.Parse(#"
<table>
<column name=""Total"" size=""0"">
<column name=""Users"" size=""0"" />
</column>
<column name=""Date"" size=""0"" />
<column name=""Unique"" size=""0"">
<column name=""Clicks"" size=""0"">
<column name=""RC"" size=""0"" />
<column name=""CB"" size=""0"" />
</column>
</column>
</table>");
List<List<XElement>> outerList = new List<List<XElement>>();
IEnumerable<XElement> innerList = root.Elements();
while (innerList.Any())
{
outerList.Add(innerList.Select(e => new XElement(e.Name, e.Attributes())).ToList());
innerList = innerList.SelectMany(element => element.Elements());
}
Note: For the record, your intuition that you should use recursion was correct. However, it is also well known that any recursive function can be converted to an iteration, typically by simulating the stack. Sometimes, this leads to bloated code; however, other times, the conversion lends itself naturally. In your case, if you were to recurse, your recursive parameter would have been the immediate children of the set of elements currently being considered – which already happens to be available in innerList, thus allowing us to use the innerList = innerList.<SequenceOperation> trick to substitute the recursion.