how to get the string value and save it in database - spring

I am using spring form tags and hibernate..
my jsp page has the follwoing code:
<tr><td><form:input path="userEnteredHostNameString" size="30" maxlength="200"/></td>
<td><form:input path="userEnteredDirectoryString" size="30" maxlength="200"/></td>
<td><form:input path="userEnteredUserNameString" size="20" maxlength="20"/></td>
<td><form:input path="userEnteredPasswordString" size="20" maxlength="20"/></td></tr>
getters and setters in my location.java
public String getUserEnteredHostNameString() {
return userEnteredHostNameString;
}
public void setUserEnteredHostNameString(String userEnteredHostNameString) {
if (userEnteredHostNameString!=null) userEnteredHostNameString = userEnteredHostNameString.toUpperCase();
this.userEnteredHostNameString = userEnteredHostNameString;
}
public String getUserEnteredDirectoryString() {
return userEnteredDirectoryString;
}
public void setUserEnteredDirectoryString(String userEnteredDirectoryString) {
if (userEnteredDirectoryString!=null) userEnteredDirectoryString = userEnteredDirectoryString.toUpperCase();
this.userEnteredDirectoryString = userEnteredDirectoryString;
}
public String getUserEnteredUserNameString() {
return userEnteredUserNameString;
}
public void setUserEnteredUserNameString(String userEnteredUserNameString) {
if (userEnteredUserNameString!=null) userEnteredUserNameString = userEnteredUserNameString.toUpperCase();
this.userEnteredUserNameString = userEnteredUserNameString;
}
public String getUserEnteredPasswordString() {
return userEnteredPasswordString;
}
public void setUserEnteredPasswordString(String userEnteredPasswordString) {
if (userEnteredPasswordString!=null) userEnteredPasswordString = userEnteredPasswordString.toUpperCase();
this.userEnteredPasswordString = userEnteredPasswordString;
}
In my controller, I have the following code:
FtpScanEvents f = new FtpScanEvents();
if(location.getUserEnteredHostNameString()!=null){
f.setHostName(location.getUserEnteredHostNameString());
}
if(location.getUserEnteredDirectoryString()!=null){
f.setDirectory(location.getUserEnteredDirectoryString());
}
if(location.getUserEnteredUserNameString()!=null){
f.setUserName(location.getUserEnteredUserNameString());
}
if(location.getUserEnteredPasswordString()!=null){
f.setPassword(location.getUserEnteredPasswordString());
}
ftpDao.save(f);
FtpScanEvents table has hostName, directory, username, password, locationId, idx, Id as columns..
hbm mapping file for ftpscanevents:
<hibernate-mapping package="ca.ups.tundra.model">
<class name="FtpScanEvents" table="FTP_SCAN_EVENTS">
<id name="id" type="long">
<generator class="native"/>
</id>
<property name="hostName" type="string" column="HOSTNAME" length="200"/>
<property name="directory" type="string" column="DIRECTORY" length="200"/>
<property name="userName" type="string" column="USERNAME" length="20"/>
<property name="password" type="string" column="PASSWORD" length="20"/>
<many-to-one name="location" class="Location" cascade="all">
<column name="ID" not-null="true" />
</many-to-one>
</class>
</hibernate-mapping>
save(e entity) code..
#Override
#Transactional(propagation = Propagation.MANDATORY)
public void save(E entity) {
if(entity == null)
throw new NullArgumentException("entity");
Session s = sessionFactory.getCurrentSession();
s.saveOrUpdate(entity);
}
when it comes to ftpDao.save(f); program terminates and there are no errors in the console..any suggestion is greatly appreciated..

In the save method, I was missing a property. Added that property with a if condition and it worked!

Related

REST Web API post related entities

Hi CodeFluent enthusiasts!
I have these two related entities in my model:
<cf:entity name="Main" defaultUsePersistenceDefaultValue="false" namespace="idscommerce" categoryPath="/idscommerce">
<cf:property name="Id" key="true" />
<cf:property name="Nom" />
<cf:property name="Ordre" />
<cf:property name="URL" />
<cf:property name="Icona" />
<cf:property name="Texts" typeName="{0}.MainTextCollection" relationPropertyName="Main" dataMember="true" />
<cf:entity name="MainText" defaultUsePersistenceDefaultValue="false" namespace="idscommerce" categoryPath="/idscommerce">
<cf:property name="Id" key="true" />
<cf:property name="Text" />
<cf:property name="Idioma" typeName="{0}.Idioma" relationPropertyName="MainTexts" />
<cf:property name="Main" typeName="{0}.Main" relationPropertyName="Texts" />
In my API, GET is working right, but when I POST (I'm using the [FromBody]Main value option) it goes into a loop at LoadByMain method from MainTextCollection.
// GET api/Main/id
public Main Get(string id)
{
idscommerce.Main value = idscommerce.Main.LoadByEntityKey(id);
if(value == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return value;
}
// POST api/Main
public HttpResponseMessage Post([FromBody]Main value)
{
if(value == null || !value.Save())
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
return Request.CreateResponse(HttpStatusCode.OK, value);
}
What it's weird is that the same class works as expected when calling from Main.LoadAll() or Main.LoadById(id), but it's going into an endless loop when called from the API POST method using Post([FromBody]Main value).

Navigation property values not added to entity

I've a WebAPI OData v3 (5.6.3) service (without EF) which I call from breeze using server side metadata. Unfortunately I cannot get navigation properties to load correctly in breeze.
The model is defined as following:
public class ParentItem
{
private readonly List<ChildItem> childItems = new List<ChildItem>();
[Key]
public int Id { get; set; }
public virtual ICollection<ChildItem> ChildItems
{
get
{
return this.childItems;
}
}
#endregion
}
public class ChildItem
{
[Key]
public int Id { get; set; }
[ForeignKey("ParentItem")]
public int? ParentItemId { get; set; }
public virtual ParentItem ParentItem { get; set; }
}
These are the metadata generated by the server:
<?xml version="1.0" encoding="utf-8"?>
<edmx:Edmx Version="1.0" xmlns:edmx="http://schemas.microsoft.com/ado/2007/06/edmx">
<edmx:DataServices m:DataServiceVersion="3.0" m:MaxDataServiceVersion="3.0" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
<Schema Namespace="Solutions2Share.Solutions.MeetingManagerWeb.Models" xmlns="http://schemas.microsoft.com/ado/2009/11/edm">
<EntityType Name="ParentItem">
<Key>
<PropertyRef Name="Id" />
</Key>
<Property Name="Id" Type="Edm.Int32" Nullable="false" />
<NavigationProperty Name="ChildItems" Relationship="MyNamespace_ChildItem_ChildItemsPartner" ToRole="ChildItems" FromRole="ChildItemsPartner" />
</EntityType>
<EntityType Name="ChildItem">
<Key>
<PropertyRef Name="Id" />
</Key>
<Property Name="Id" Type="Edm.Int32" Nullable="false" />
<Property Name="ParentId" Type="Edm.Int32" />
<NavigationProperty Name="ParentItem" Relationship="MyNamespace_ParentItem_ParentItemPartner" ToRole="ParentItem" FromRole="ParentItemPartner" />
</EntityType>
<Association Name="MyNamespace_ChildItem_ChildItemsPartner">
<End Type="MyNamespace.ChildItem" Role="ChildItems" Multiplicity="*" />
<End Type="MyNamespace.ParentItem" Role="ChildItemsPartner" Multiplicity="0..1" />
</Association>
<Association Name="MyNamespace_ParentItem_ParentItemPartner">
<End Type="MyNamespace.ParentItem" Role="ParentItem" Multiplicity="0..1" />
<End Type="MyNamespace.ChildItem" Role="ParentItemPartner" Multiplicity="0..1" />
</Association>
<EntityContainer Name="Container" m:IsDefaultEntityContainer="true">
<EntitySet Name="ParentItems" EntityType="MyNamespace.ParentItem" />
<EntitySet Name="ChildItems" EntityType="MyNamespace.ChildItem" />
<AssociationSet Name="MyNamespace_ChildItem_ChildItemsPartnerSet" Association="MyNamespace_ChildItem_ChildItemsPartner">
<End Role="ChildItemsPartner" EntitySet="ParentItems" />
<End Role="ChildItems" EntitySet="ChildItems" />
</AssociationSet>
<AssociationSet Name="MyNamespace_ParentItem_ParentItemPartnerSet" Association="MyNamespace_ParentItem_ParentItemPartner">
<End Role="ParentItemPartner" EntitySet="ChildItems" />
<End Role="ParentItem" EntitySet="ChildItems" />
</AssociationSet>
</EntityContainer>
</Schema>
</edmx:DataServices>
</edmx:Edmx>
I'm using webApiOData on the client:
breeze.config.initializeAdapterInstance('dataService', 'webApiOData', true);
The query which I'm execute looks like this:
breeze.EntityQuery().from('ParentItems').expand('ChildItems');
The server call returns the correct items:
{
"odata.metadata":"http://example.com/api/$metadata#ParentItems","value":[
{
"odata.type":"MyNamespace.ParentItem","odata.id":"http://example.com/api/ParentItems(1)","ChildItems#odata.navigationLinkUrl":"http://example.com/api/ParentItems(1)/ChildItems","ChildItems":[
{
"odata.type":"MyNamespace.ChildItem","odata.id":"http://example.com/api/ChildItems(1)","ParentItem#odata.navigationLinkUrl":"http://example.com/api/ChildItems(1)/ParentItem","Id":1,"ParentItemId":1
},{
"odata.type":"MyNamespace.ChildItem","odata.id":"http://example.com/api/ChildItems(2)","ParentItem#odata.navigationLinkUrl":"http://example.com/api/ChildItems(2)/ParentItem","Id":2,"ParentItemId":1
}
],"Id":1
}
]
}
But the ChildItems property of the ParentItem entity is empty.
Edit: If I call manager.getEntities()after executing the query all parent and child items are returned.

Unable to do form validation in spring

I am trying to do validation in spring mvc. I have added the hibernate-validator-4.0.2.GA. jar and validation-api-1.0.0GA.jar but i am getting exception
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'contact' available as request attribute
org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:141)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:174)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:194)
org.springframework.web.servlet.tags.form.LabelTag.autogenerateFor(LabelTag.java:129)
org.springframework.web.servlet.tags.form.LabelTag.resolveFor(LabelTag.java:119)
org.springframework.web.servlet.tags.form.LabelTag.writeTagContent(LabelTag.java:89)
org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:102)
org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:79)
org.apache.jsp.WEB_002dINF.jsp.contact_jsp._jspx_meth_form_005flabel_005f0(contact_jsp.java:250)
org.apache.jsp.WEB_002dINF.jsp.contact_jsp._jspService(contact_jsp.java:103)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1060)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:798)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:647)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:552)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.apache.jasper.runtime.PageContextImpl.doForward(PageContextImpl.java:745)
org.apache.jasper.runtime.PageContextImpl.forward(PageContextImpl.java:716)
org.apache.jsp.index_jsp._jspService(index_jsp.java:71)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
Contact.jsp
<form:form method="get" action="addContact.html" modelAttribute="contact">
<table>
<tr>
<td><form:label path="firstname">First Name</form:label></td>
<td><form:input path="firstname" /></td>
<form:errors path="firstname"></form:errors>
</tr>
<tr>
<td><form:label path="lastname">Last Name</form:label></td>
<td><form:input path="lastname" /></td>
<form:errors path="lastname"></form:errors>
</tr>
<tr>
<td><form:label path="email">Email</form:label></td>
<td><form:input path="email" /></td>
<form:errors path="email"></form:errors>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Add Contact"/>
</td>
</tr>
</table>
Contact.java
public class Contact {
#NotEmpty
private String firstname = null;
#NotEmpty
private String lastname = null;
#NotEmpty
private String email=null;
/*#NotEmpty
#Min(1)
#Max(110)
private int telephone*/;
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
ContactController.java
#Controller
#SessionAttributes
public class ContactController {
#RequestMapping(value = "/addContact", method = RequestMethod.GET)
public String addContact( #Valid #ModelAttribute("contact")
Contact contact, BindingResult
result,ModelMap model){
model.addAttribute("contact", new Contact());
if(result.hasErrors()) {
System.out.println("Hiii i am validator");
return "contact";
}
model.addAttribute("message", "Successfully saved person: " + contact.toString());
model.addAttribute("name",contact.getFirstname());
model.addAttribute("surname",contact.getLastname());
// model.addAttribute("age",contact.getTelephone());
model.addAttribute("email",contact.getEmail());
System.out.println("First Name:" + contact.getFirstname() +
"Last Name:" + contact.getLastname());
return "result";
}
#RequestMapping("/contacts")
public ModelAndView showContacts() {
return new ModelAndView("contact", "command", new Contact());
}
}
web.xml
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
spring-servlet.xml
<context:component-scan base-package="com.demo.Controller" />
<mvc:annotation-driven />
<context:annotation-config />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/messages" />
</bean>
I have also tried using commandName instead of modelattribute but still i get the same exception and also tried using both get and post methods.
1 - Create a new Contact instance before loading your Contact.jsp
#RequestMapping("/contacts")
public ModelAndView showContacts() {
ModelAndView m = new ModelAndView("contact");
m.add("contact", new Contact());
return m;
}
2 - Ensure you are invoking the right servlet path :
#RequestMapping(value = "/addContact", method = RequestMethod.GET)
and change it in you form's header:
<form:form method="get" action="addContact" modelAttribute="contact">
Some further information about this error here
I already had this error before and the problem was that I didn't put a simple domain object like your "Contact" in tha Model, while my Spring form was waiting a domain object.
Try to do something like :
model.addAttribute("contact", new contact());
And that should work.

Problems with Hibernate Validator and Spring Webflow

I'm trying to validate a form using Spring WebFlow and Hibernate Validator Annotations, but I'm doing something wrong.
If I use the Spring validation way (ValidationContext, MessageContext, validate${state}, etc), all works fine, but I want to use the Hibernate Annotations like #Email, #NotEmpty, etc.
I've read a lot of forums, Spring documentation, but I don't know what I'm doing wrong.
At this moment, this is my view-state and next action code:
<var name="user" class="myproject.web.pojo.User"/>
<view-state id="startSignup" model="user">
<binder>
<binding property="email" />
<binding property="name" />
<binding property="lastName" />
<binding property="password" />
</binder>
<on-entry>
<set name="flowScope.user" value="new info.teaming.web.pojo.User()" />
</on-entry>
<transition on="dataEntered" to="lookupUser" />
</view-state>
<action-state id="lookupUser">
<evaluate expression="signupActions.lookupUser(user)" />
<transition to="startSignup" on-exception="myproject.web.service.exception.UserAlreadyExistsException" />
<transition to="saveOrder" />
</action-state>
(...)
This is the startSignup.jsp code:
<!-- sf:form method="POST" modelAttribute="user" -->
<sf:form method="POST" commandName="user" >
<input type="hidden" name="_flowExecutionKey" value="${flowExecutionKey}" />
<fieldset>
<table cellspacing="0">
<tr>
<th>
<label for="name"><fmt:message key="signUp.name"/></label>
</th>
<td>
<sf:input path="name" size="25" id="name" />
</td>
<sf:errors path="name" />
</tr>
<tr>
<th>
<label for="lastName"><fmt:message key="signUp.lastName"/></label>
</th>
<td>
<sf:input path="lastName" size="45" maxlength="45" id="lastName" />
</td>
</tr>
<tr>
<th>
<label for="password"><fmt:message key="signUp.password"/></label>
</th>
<td>
<sf:password path="password" size="20" showPassword="true" id="password" />
</td>
</tr>
<tr>
<th>
<label for="email"><fmt:message key="signUp.email"/></label>
</th>
<td>
<sf:input path="email" size="30" id="email" />
</td>
</tr>
<tr>
<td>
<input type="submit" name="_eventId_dataEntered" value="<fmt:message key="signUp.register"/>"/>
</td>
</tr>
</table>
</fieldset>
</sf:form>
This is the myproject.web.pojo.User POJO code:
import java.io.Serializable;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#NotEmpty
#Length(min = 2, max = 25)
private String name;
#NotEmpty
#Email
private String email;
#NotEmpty
#Length(min = 2, max = 45)
private String lastName;
#NotEmpty
#Length(min = 6, max = 20)
private String password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public void setPassword(String password) {
this.password = password;
}
public String getPassword() {
return password;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
// public void validateStartSignup(ValidationContext context) {
// MessageContext messages = context.getMessageContext();
//
// messages.addMessage(new MessageBuilder().error().source("name").code("user.name.notEmpty").build());
// }
}
(note: as you can see, when I work with Spring Validation (uncomment the validate method), the form validates successfully)
And finally, this is my SignupAction code:
import myproject.web.model.UsrUser;
import myproject.web.model.dao.UsrUserDAO;
import myproject.web.pojo.User;
import myproject.web.service.exception.UserAlreadyExistsException;
import javax.annotation.Resource;
import javax.validation.Valid;
import org.springframework.stereotype.Component;
import org.springframework.webflow.action.MultiAction;
import org.springframework.webflow.execution.Event;
#Component
public class SignupActions extends MultiAction {
#Resource
UsrUserDAO usrUserDAO;
private static final long serialVersionUID = 1L;
public Event lookupUser(#Valid User user) throws UserAlreadyExistsException {
try {
usrUserDAO.findByEmail(user.getEmail());
} catch (javax.persistence.NoResultException e) {
return success();
}
throw new UserAlreadyExistsException();
}
public void saveUser(UsrUser user) {
return;
}
}
When I work with Hibernate Validation, the flow arrives to the saveUser method, without any validation.
I'm using Spring 3:
Spring 3.0.5.RELEASE
Spring WebFlow 2.2.1.RELEASE
Hibernate Validator 4.0.2.GA
What I'm doing wrong?
Thanks a lot for helping me! :)
have you defined your validator in Spring configuration XML file?
According to Spring Webflow reference it shoud be defined like this:
<webflow:flow-registry flow-builder-services="flowBuilderServices" />
<webflow:flow-builder-services id="flowBuilderServices" validator="validator" />
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
Try,
Changing:
#Resource
UsrUserDAO usrUserDAO;
By:
#Autowired
private UsrUserManager UsrUserManager;
Using MVC manager.
And:
#Transactional
public Event lookupUser(#Valid User user) throws UserAlreadyExistsException { ...
as a Spring MVC controller, or reusing this MVC code if you already desing it ;)

DataServieException: Oracle, EFOracleProvider, POCO and EF 4.0

I try to use the new POCO capabilities of EF 4.0 in combination with the EFOracleProvider. I have recompiled the EFOracleProvider (using ODAC instead of System.Data.OracleClient) to target the .NET Framework 4 (und put it in the 4.0 GAC). Everything ok so far.
I host the Entity Model in a WCF Data Service:
class DivaDispoDataService : DataService<DivaDispoContainer>
{
public static void InitializeService(IDataServiceConfiguration config)
{
config.SetEntitySetAccessRule("*", EntitySetRights.All);
config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);
}
}
My EDMX File looks like this:
<?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" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" Namespace="DivaDispo.Store" Alias="Self" Provider="EFOracleProvider" ProviderManifestToken="10g">
<EntityContainer Name="DivaDispoStoreContainer">
<EntitySet Name="DIW_USER" EntityType="DivaDispo.Store.DIW_USER" store:Type="Tables" Schema="" />
</EntityContainer>
<EntityType Name="DIW_USER">
<Key>
<PropertyRef Name="IDX" />
</Key>
<Property Name="IDX" Type="number" Nullable="false" Precision="10" />
<Property Name="USERNAME" Type="number" Precision="10" />
<Property Name="PERSONNELNUMBER" Type="number" Precision="10" />
<Property Name="PASSWORD" Type="varchar2" MaxLength="10" />
<Property Name="ACTIVATED" Type="number" Precision="1" />
<Property Name="ROLE" Type="number" Precision="1" />
</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="DivaDispo.Model" Alias="Self" xmlns:annotation="http://schemas.microsoft.com/ado/2009/02/edm/annotation">
<EntityContainer Name="DivaDispoContainer" annotation:LazyLoadingEnabled="false">
<EntitySet Name="User" EntityType="DivaDispo.Model.User" />
</EntityContainer>
<EntityType Name="User">
<Key>
<PropertyRef Name="ID" />
</Key>
<Property Name="ID" Type="Decimal" Nullable="false" Precision="10" Scale="0" />
<Property Name="Username" Type="Decimal" Precision="10" Scale="0" />
<Property Name="PersonnelNumber" Type="Decimal" Precision="10" Scale="0" />
<Property Name="Password" Type="String" MaxLength="10" Unicode="false" FixedLength="false" />
<Property Name="Activated" Type="Boolean" />
<Property Name="Role" Type="Boolean" />
</EntityType>
</Schema>
</edmx:ConceptualModels>
<!-- C-S mapping content -->
<edmx:Mappings>
<Mapping xmlns="http://schemas.microsoft.com/ado/2008/09/mapping/cs" Space="C-S">
<EntityContainerMapping StorageEntityContainer="DivaDispoStoreContainer" CdmEntityContainer="DivaDispoContainer">
<EntitySetMapping Name="User">
<EntityTypeMapping TypeName="IsTypeOf(DivaDispo.Model.User)">
<MappingFragment StoreEntitySet="DIW_USER">
<ScalarProperty Name="ID" ColumnName="IDX" />
<ScalarProperty Name="Username" ColumnName="USERNAME" />
<ScalarProperty Name="PersonnelNumber" ColumnName="PERSONNELNUMBER" />
<ScalarProperty Name="Password" ColumnName="PASSWORD" />
<ScalarProperty Name="Activated" ColumnName="ACTIVATED" />
<ScalarProperty Name="Role" ColumnName="ROLE" />
</MappingFragment>
</EntityTypeMapping>
</EntitySetMapping>
</EntityContainerMapping>
</Mapping>
</edmx:Mappings>
</edmx:Runtime>
</edmx:Edmx>
My POCO Class looks like this:
public partial class User
{
public virtual decimal ID { get; set; }
public virtual Nullable<decimal> Username { get; set; }
public virtual Nullable<decimal> PersonnelNumber { get; set; }
public virtual string Password { get; set; }
public virtual Nullable<bool> Activated { get; set; }
public virtual Nullable<bool> Role { get; set; }
}
and the DataContext like this:
public partial class DivaDispoContainer : ObjectContext
{
public const string ConnectionString = "name=DivaDispoContainer";
public const string ContainerName = "DivaDispoContainer";
#region Constructors
public DivaDispoContainer()
: base(ConnectionString, ContainerName)
{
this.ContextOptions.LazyLoadingEnabled = false;
}
public DivaDispoContainer(string connectionString)
: base(connectionString, ContainerName)
{
this.ContextOptions.LazyLoadingEnabled = false;
}
public DivaDispoContainer(EntityConnection connection)
: base(connection, ContainerName)
{
this.ContextOptions.LazyLoadingEnabled = false;
}
#endregion
#region ObjectSet Properties
public ObjectSet<User> User
{
get { return _user ?? (_user = CreateObjectSet<User>("User")); }
}
private ObjectSet<User> _user;
}
The POCO classes and the DataContext are generated with the POCO Template from Visual Studio 2010.
When I start my WCF Service and want to query the users I receive an System.Data.Services.DataServiceException which says somtihng like
500: Internal Server error. The type 'System.Data.Entity.DynamicProxies.User_057822846B2B8DD7BB03058490B27D19E6C634EACF33438FE886 19C8BBB1CF74' is not a komplex type or entity type.
When I look in the dubgger I can see that the values have been read from the database (therefore I think the EFOracleProvider works ok) and that the DynamicProxies.User_.... is derrived from my User class (which contains at that point the data from the database). So the question is: Why do I receive this exception? Does anyone know whats going on there? What's the DynamicProxies.User_.... automaic generated class for? The Exception is thrown in the Method GetNonPrimitiveResourceType of the class WebUtil. Or maybe I have something overlooked?
Any help greatly appreciated....
The link from Craig to the blog post http://msdn.microsoft.com/en-us/library/ee705457.aspx revealed the answer. It states there that
The POCO proxy type cannot be directly serialized or deserialized by WCF
and that is exactly my problem. If I remove the virtual from the properties of the genrated POCO class the runtime doesnt generate the proxy types and the exception dissapears.
Thanks again for the link, Craig.

Resources