Error Saving ViewState in Entity Framework - c#

I am working in .NET Entity Framework 4.0
I am using viewstate to save an entity. And I have serialize that entity as well. But when I try to save data to viewstate, getting this error:
Microsoft JScript runtime error: Sys.WebForms.PageRequestManagerServerErrorException: Error serializing value 'System.Collections.Generic.List`1[Pc.PrecisionCare2.ModelTypes.Medication]' of type 'System.Collections.Generic.List`1[[Pc.PrecisionCare2.ModelTypes.Medication, PrecisionCare2ModelTypes, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].'

Maybe this will help anyone. I wanted to serialize a entity in the Viewstate myself and couldn't find a good solution (XMLSerialization, Byte Serializing, DataContract). What I found out is that I could "extend" the code generated classes (they are partial) and make it Serializable.
For example this is a .net code generated entity:
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace OAuthServerBroker.EF
{
using System;
using System.Collections.Generic;
public partial class ResourceOwner
{
public ResourceOwner()
{
this.Grant = new HashSet<Grant>();
}
public System.Guid ResourceOwner_ID { get; set; }
public string ResourceOwner_Username { get; set; }
public virtual ICollection<Grant> Grant { get; set; }
}
}
When I create a new class file with the same class name and namespace I can make the Entity Serializable :).
using System;
namespace OAuthServerBroker.EF
{
[Serializable]
public partial class ResourceOwner
{
public EntityState State { get; set; } //can even put into new properties
}
}
Hope this might help anyone since it's an old post :(.

Related

C# EF Required Attribute not recognized

I am creating an app that uses a database (SQLite). I am using entity framework and ADO.NET to interact with it.
I have a seprate Models project in my app that contains all of my Database models.
Now I want to mark some of my class properties as required to reflect the "NOT NULL" option in my database. But if I add the [Required] Attribute from DataAnnotations namespace I get a compiler error saying it cannot be resolved.
Here is how my class looks like :
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace ReflowModels
{
public class Tag
{
public Tag()
{
this.Options = new HashSet<Option>();
}
public int Id { get; set; }
[Required]
public string Name { get; set; }
public ICollection<Option> Options { get; set; }
}
}
I have also added a reference to EntityFramework.dll in my project.
you need to add this to your using block
using System.ComponentModel.DataAnnotations.Schema;
you need to add this to your using block
using System.ComponentModel.DataAnnotations;
In case it still doesn't work, maybe you should add it to your References

what 's the use of creating a metadata class and a partial class for the model class c#

I just joined a new company and my manager just joined too, and he wants to change the way we program. basically do what he does. I'm wondering what's the difference, pros, cons, limitation and problems if there'll be any..here's the sample
namespace Models //this is the model part of from edmx
{
using System;
using System.Collections.Generic;
public partial class MyModelClass
{
public int ID { get; set; }
public Nullable<System.DateTime> PostDate { get; set; }
public string MyContent { get; set; }
}
}
this is the metadata:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Models
{
public class MyModelMetaData
{
//he wants all data annotation here
public int ID { get; set; }
public Nullable<System.DateTime> PostDate { get; set; }
public string MyContent { get; set; }
}
}
this is the partial:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Models
{
[MetadataType(typeof(MyModelMetaData))]
public partial class MyModelClass or MyModelClassPartial
{
//He wants the programming algorithm to go here
}
}
Please enlightened me. and he wants to create different metadata and partial classes per model class..way too many files involved.
thank you..i need an answer as to why..if you think his method is good..I will do this..but if you think this will cause problem in the future and more coding will be involve..i need to know
The first class you show, the entity classes, are generated from the database every time you save the EDMX (or when you execute the T4 Template).
This causes the file containing public partial class MyClass under the EDMX to be regenerated. So you cannot alter it, because the next time someone refreshes a table or adds one, your changes are gone.
That's why entity classes are generated as a partial: so you can create another partial to the same class to do your modifications in.
However, if you want to annotate your entity's properties with metadata, you cannot redefine the same property in the other partial class: the same name can only be used by one member of a type. So you can't do this:
// Entity class
public partial class FooEntity
{
public string Name { get; set;}
}
// User-created partial class
public partial class FooEntity
{
[Required]
public string Name { get; set;}
}
Because that code expresses you want two properties named Name in the FooEntity class, which is not valid.
So you'll have to come up with another way to add metadata to the type. Enter the [MetadataType] attribute. This works by creating a new class with the same properties as the class to be annotated. Here, using reflection, the metadata is resolved based on member name.
So when you create a metadata class for the above annotation:
public class FooEntityMetadata
{
[Required]
public string Name { get; set;}
}
You can apply it to the user-created partial:
// User-created partial class
[MetadataType(typeof(FooEntityMetadata))]
public partial class FooEntity
{
}
And also, in the latter partial, you can add members that add functionality to the entity model. New ([NotMapped]) properties and new methods for example.
I think the one use could be to not pollute the main class.
For example if you have a lot of attribute for validation (using dataannotation) and you don't want to have them in the main class you could use the MetadataTypeAttribute for that.
Another use could be if your class is auto-generated and you need to add some decoration (more attributes) to your properties without changing the autogenerated code.

Partial Class to a generated class in EF bug?

I am used to VB and is kind of new to C# syntax. But from what I read everywhere the syntax seems to be kind of identical for Partial Classes.
I am trying to make a partial class to a generated partial class generated with Entity Framework.
It seems like my class can't reach the other one.
The error:
'XmasMVC.CmsSystemPagePart' does not contain a definition for
'DefaultLanguageCode' and no extension method 'DefaultLanguageCode'
accepting a first argument of type 'XmasMVC.CmsSystemPagePart' could
be found (are you missing a using directive or an assembly reference?)
I can compile but then I get errors while running. Seems like my class overwrites the generated one.
This is the genereated class from EF.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace XmasMVC
{
using System;
public partial class CmsSystemPagePart
{
public string DefaultLanguageCode { get; set; }
public string PagePartName { get; set; }
public string Description { get; set; }
public string DefaultLangValue { get; set; }
public string LanguageCode { get; set; }
public string Value { get; set; }
}
}
This is my class.
namespace XmasMVC
{
using System;
public partial class CmsSystemPagePart
{
public string GetValue()
{
if (this.Value == null)
return this.DefaultLangValue;
else return this.Value;
}
public string GetLanguageCode()
{
if (this.Value == null)
return this.DefaultLanguageCode;
else return this.LanguageCode;
}
}
}
Found this "Warning":
"The type 'XmasMVC.CmsSystemPagePart' >in 'C:\VSS\Comdigit\Xmas\XmasMVC\App_Code\CmsSystemPagePart.cs' conflicts with the imported >type 'XmasMVC.CmsSystemPagePart' in 'C:\VSS\Comdigit\Xmas\XmasMVC\'. Using the type defined >in 'C:\VSS\Comdigit\Xmas\XmasMVC\App_Code\CmsSystemPagePart.cs"
This is how the Objects Browser looks like. Strange for me!
This link here explains that
In general, ASP.NET creates an assembly for each application directory (such as App_Code) and one for the main directory.
For your case, although the partial classes are in the same project and the same namespace they are not being compiled into the same assembly.
Try moving the source files out of App_Code and make sure their Build action is Compiled in the properties window.

Data Annotations with Entity Framework 5.0 (database first)

What is the best way to use data annotations for validation if I'm using an Entity Framework (v5.0) database first approach?
This is my partial class created by Entity Framework:
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System.ComponentModel.DataAnnotations;
namespace ACore
{
using System;
using System.Collections.Generic;
public partial class PayrollMarkup_State
{
[UIHint("StatesEditor")] // <-- I added this line but it will be overwritten
public string State { get; set; }
public Nullable<float> MaintenancePercentage { get; set; }
public Nullable<float> OfficePercentage { get; set; }
}
}
I tried this with no success....
Entity Framework generated file: 'PayrollMarkup_State.cs'
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System.ComponentModel.DataAnnotations;
namespace ACore
{
using System;
using System.Collections.Generic;
public partial class PayrollMarkup_State
{
public string State { get; set; }
public Nullable<float> MaintenancePercentage { get; set; }
public Nullable<float> OfficePercentage { get; set; }
}
}
I then created this file in a different directory: 'PayrollMarkup_state.cs'
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace ACore.Models
{
[MetadataType(typeof(PayrollMarkupMetadata))]
public partial class PayrollMarkup_State
{
}
public class PayrollMarkupMetadata
{
[UIHint("StatesEditor")]
public string State; // Has to have the same type and name as your model
}
}
Although it's somewhat painful, you need to create a class to use as the MetadataType for your model class.
[MetadataType(typeof(PayrollMarkupMetadata))
public partial class PayrollMarkup_State
{
...
}
public class PayrollMarkupMetadata
{
[UIHint("StatesEditor")]
public string State; // Has to have the same type and name as your model
// etc.
}
You have a namespace problem - you have defined two different PayrollMarkup_State classes, one under the ACore namespace and one under the ACore.Models namespace. Change the namespace to ACore (from ACore.Models) in the file containing the metadata type definition.
You can use a partial metadata class
http://www.asp.net/mvc/overview/getting-started/database-first-development/enhancing-data-validation
I used two additional classes: Map and Meta, here is my map:
namespace Whatever.Models
{
[MetadataType(typeof(ThisMeta))]
public partial class This
{
}
}
now here is meta class:
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace Whatever.Models
{
public class ThisMeta
{
[DisplayName("")]
public int UID { get; set; }
}
}

Entity Framework DbContext code generation generates incorrect code

I'm using VS2010 with Entity Framework (file version is 4.4. product version is 5)
I have installed the EF5.x DbContext generator.
After creating my .edmx file, I right clicked on the empty space and added a new DbContext template, which generated the context.tt and .tt files.
However, in the .tt files, this is how the auto generated code looks like:
namespace DataObjects.EntityFramework.Models
{
using System;
using System.Collections.Generic;
public partial class SubSystem
{
public string SubSystemId { get; set; }
public string Description { get; set; }
public string Fmode { get; set; }
public Nullable<System.DateTime> LastBackup { get; set; }
}
}
The problem is that the using statements are inside the namespace, which gives rise to a compilation error.
Those compilation errors must be related to something else, because it's perfectly legal in C# to have using statements in the namespace.
Verify that you've added all of the correct references, such as EntityFramework.dll

Categories