Generate DataAnnotations With Fluent API And ObjectContext?

Apr 4, 2011

I'm building an application using MVC 3 and Entity Framework 4. I've created my Entity Data Model and generated a database from it. Now I know the validation attributes such as [Required] or [StringLength(5)] can be used on the model properties to provide validation both clientside and serverside.

I would like to know if these attributes can also be generated dynamically instead of having to add them to the model explicitly? I saw that in EF 4.1 RC you can make use of the Fluent API to further configure your model in the OnModelCreating method by using the DbModelBuilder class. As shown here I'm working with a framework however that still uses ObjectContext instead of DbContext so I would like to know if the above solution can be used in combination with ObjectContext?

As a final note, since I've been trying to figure out how to generate and use data annotations it seems using view models would increase the complexity of validation. From what I read here it seems that just passing the models directly to the view would remove the need to add annotations to the models as well as the view models. However that means that you can no longer use strongly typed views when you do joins on the models and pass those to the view directly?

View 1 Replies


Similar Messages:

How To Test Generate Tables With Fluent Nhibernate (schemaexport)

Nov 17, 2010

this is my very very first project with fluent hibernate.i've had small experience in hibernate and nhibernate:

This context is completely new to me since this is a web app project.

So i have my webapp project with most of the fluent nhibernate found on the net.

so i have This entities:

[code]....

View 1 Replies

ADO.NET :: The Constructor Of ObjectContext

Mar 8, 2011

I am confused about the constructor of ObjectContext

// Summary:
// Initializes a new instance of the System.Data.Objects.ObjectContext class
// with a given connection string and entity container name.
//
// Parameters:
// connectionString:
// The connection string, which also provides access to the metadata information.
//
// defaultContainerName:
// The name of the default entity container. When the defaultContainerName is
// set through this method, the property becomes read-only.
protected ObjectContext(string connectionString, string defaultContainerName);

I am not understanding the parameters clearly.

View 3 Replies

Entity Framework - ObjectContext?

Mar 3, 2011

im working with a proyect made in ASP.Net using Webforms. Im using Entity Framework to save data on Microsoft SQL.

My question is:

Is posible to use a Static class to keep the ObjectContext of EF live and put/get entities NOT saved inside the ObjectContext??

I wan to create an Object, then added with AddObject on the ObjectContext, But NOT to do the Savechanges. All this in one webform An then, in other webform, access to the ObjectContext and Get the Object added

View 3 Replies

EF4 - Add Object To Objectcontext Without Save Changes?

Oct 29, 2010

I have a page like Order - Order lines. Order represents by some textboxes and ddls, Order lines represents by GridView.

I want to let users add order lines without save changes to database. For example: he adds 4 order lines, fill order info and then hits Save button. Only an that moment all information should be saved to DB.

When I use code like

using (Entities ctx = new Entities())
{
//create new OrderLine
OrderLine ol = OrderLine.CreateOrderLine(1, 1, "", 1);
//add OrderLine to OrderLines collection
ctx.CreateOrderLines.AddObject(ol);
}

newly created OrderLine does not appears in my object context, so I can't access it and bind GridView to new OrderList collection.

How can I solve this problem? Or maybe there are another ways to perform this task?

View 1 Replies

.net - Entity Framework ObjectContext Re-usage?

Apr 27, 2010

I'm learning EF now and have a question regarding the ObjectContext: Should I create instance of ObjectContext for every query (function) when I access the database? Or it's better to create it once (singleton) and reuse it? Before EF I was using enterprise library data access block and created instance of dataacess for DataAccess function...

View 5 Replies

DataSource Controls :: EF4 - Function Imports In ObjectContext

May 19, 2010

If I create a new EDMX model and then I import a function, then I can see my function generated in the Designer. If I perform the same process but I add a T4 template (for Self-Tracking Entities) then I loose the function definition, although TT file has code adding a region named "Function Imports". Is this a bug or am I performing something wrong?

View 1 Replies

Entity Framework ObjectContext With Dependency Injection?

Jan 6, 2011

Here's what I want to do:

UI layer: An ASP.NET webforms website.

BLL: Business logic layer which calls the repositories on DAL.

DAL: .EDMX file (Entity Model) and ObjectContext with Repository classes which abstract the CRUD operations for each entity.

Entities: The POCO Entities. Persistence Ignorant. Generated by Microsoft's ADO.Net POCO Entity Generator.

I'd like to create an obejctcontext per HttpContext in my repositories to prevent performance/thread [un]safety issues.

public MyDBEntities ctx
{
get
{
string ocKey = "ctx_" + HttpContext.Current.GetHashCode().ToString("x");
if (!HttpContext.Current.Items.Contains(ocKey))
HttpContext.Current.Items.Add(ocKey, new MyDBEntities ());
return HttpContext.Current.Items[ocKey] as MyDBEntities ;
}
}

I don't want to access HttpContext in my DAL (Where the repositories are located). But I have to somehow pass HttpContext to DAL. based on the answer to my question here, I have to use IoC pattern.

View 1 Replies

C# - ObjectContext.ExecuteStoreCommand - Clear Parameters Between Calls?

Feb 11, 2011

I am making multiple calls to ObjectContext.ExecuteStoreCommand with different commands and different parameters, although I use the same parameter list (object) for a several of the commands. I am getting the following exception:

System.ArgumentException: The SqlParameter is already contained by another SqlParameterCollection.

Is there a way to clear parameters between calls as I would do with straight up ADO.NET?

Updated with a code sample:

string sqlDeleteWebUserGreen = "delete WebUserGreen where WebUserId = @WebUserId";
string sqlDeleteWebUserBlue = "delete WebUserBlue where WebUserId = @WebUserId";
var argsDeleteWebUserXref = new DbParameter[] {
new SqlParameter { ParameterName = "WebUserId", Value = user.WebUserId }
rowsAffectedDeleteWebUserXref += base.context.ExecuteStoreCommand(sqlDeleteWebUserGreen, argsDeleteWebUserXref);
rowsAffectedDeleteWebUserXref += base.context.ExecuteStoreCommand(sqlDeleteWebUserBlue, argsDeleteWebUserXref);

UPDATE

Basically I am unable to find any better way of doing this, so I ended up accepting the answer below. The only difference is that I simply put the creation of the parameter into a separate method, so my calls look like base.context.ExecuteStoreCommand(sqlDeleteWebUserBlue, MethodThatWillGiveMeTheParameterArray());

View 1 Replies

C# - The ObjectContext Instance Has Been Disposed And Can No Longer Be Used For Operations That Require A Connection?

Mar 19, 2011

I have this view:

@model MatchGaming.Models.ProfileQuery
@{
ViewBag.Title = "Index";

[code]...

View 2 Replies

ManyToManyMapping With Fluent Nhibernate?

Feb 16, 2011

I have a table USERS and GROUPS table.

I want to add another table UserGroups.

How can I map these tables.

View 1 Replies

ADO.NET :: How To Use Fluent Nhibernate - Finding Tutorials

Nov 9, 2010

, I want to use fluent hibernate with asp.net but couldn't find any website or tutorial for that , they're all to configure it with asp.net mvc , anyone knows any?

View 3 Replies

C# - Fluent NHibernate - Collections Not Filtering?

Aug 27, 2010

I have a session criteria statement (Fluent NHibernate) that does not seem to filter the child collection even though I have Expressions/Restrictions defined.

ICriteria criteria = session.CreateCriteria(typeof(MyClass));
criteria.CreateAlias("MyCollection", "MC");
criteria.Add(Restriction.Eq("MC.Property", value));
IList<MyClass> list = criteria.List<MyClass>();

This returns all the objects of type MyClass that have MyCollection.Property = value, however MyCollection is not filtered to MyCollection.Property = value

It seems like only the Root objects get filtered.

View 2 Replies

C# - Fluent Nhibernate No Persistor For Class Name?

Sep 9, 2010

I am getting this error even though all my mappings are pretty simple and correct. I get this error only on select classes.

View 1 Replies

Fluent NHibernate Data Caching From A Table

Feb 16, 2011

We are developing a multi-language web application with ASP.NET MVC 2 and Fluent NHibernate.Our platform will be multi-language. But just static text will be multi-language. Groups pages depends on community content whatever they use. Like Facebook.We decide to keep all language string in database. And load language when application starts.

View 1 Replies

Fluent NHibernate Cascade - Trying To Insert NULL ID?

Mar 8, 2011

I have the following models & mappings (code snippets further below).

One Competition has to have multiple CompetitionAnswers associated with it (multiple choice) from the outset.

At present, using the Fluent NHibernate mappings shown below, when I create a brand new Competition object, populate the properties, then create 3 brand new CompetitionAnswer objects and add them to the CompetitionAnswers property (property on Competition), I would expect to call Save on the session which would INSERT the 1 Competition row and 3 CompetitionAnswer rows to the DB.

However, as soon as I try to call Save on the session, it complains that CompetitionId is null and it can't insert a null into the CompetitionAnswers table for that field - which is right, it shouldn't, however, I assumed that the NHibernate would first create the Competition, then use the newly generated IDENTITY value (CompetitionId) in the CompetitionAnswers table?

[code]....

View 3 Replies

C# - (Fluent) NHibernate Security Exception - ReflectionPermission

Apr 11, 2010

I've upgraded an ASP.Net Web application to the latest build of Fluent NHibernate (1.0.0.636) and the newest version of NHibernate (v2.1.2.4000). I've checked a couple of times that the application is running in Full trust. But I keep getting the following error:

Security Exception
Description: The application attempted to perform an operation not allowed by the security policy. To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file.

Exception Details: System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.ReflectionPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[SecurityException: Request for the permission of type 'System.Security.Permissions.ReflectionPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.]
System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet) +0
System.Security.CodeAccessPermission.Demand() +54
System.Reflection.Emit.DynamicMethod.PerformSecurityCheck(Type owner, StackCrawlMark& stackMark, Boolean skipVisibility) +269
System.Reflection.Emit.DynamicMethod..ctor(String name, Type returnType, Type[] parameterTypes, Type owner, Boolean skipVisibility) +81
NHibernate.Bytecode.Lightweight.ReflectionOptimizer.CreateDynamicMethod(Type returnType, Type[] argumentTypes) +165
NHibernate.Bytecode.Lightweight.ReflectionOptimizer.GenerateGetPropertyValuesMethod(IGetter[] getters) +383
NHibernate.Bytecode.Lightweight.ReflectionOptimizer..ctor(Type mappedType, IGetter[] getters, ISetter[] setters) +108
NHibernate.Bytecode.Lightweight.BytecodeProviderImpl.GetReflectionOptimizer(Type mappedClass, IGetter[] getters, ISetter[] setters) +52
NHibernate.Tuple.Component.PocoComponentTuplizer..ctor(Component component) +231
NHibernate.Tuple.Component.ComponentEntityModeToTuplizerMapping..ctor(Component component) +420
NHibernate.Tuple.Component.ComponentMetamodel..ctor(Component component) +402
NHibernate.Mapping.Component.BuildType() +38
NHibernate.Mapping.Component.get_Type() +32
NHibernate.Mapping.SimpleValue.IsValid(IMapping mapping) +39
NHibernate.Mapping.RootClass.Validate(IMapping mapping) +61
NHibernate.Cfg.Configuration.ValidateEntities() +220
NHibernate.Cfg.Configuration.Validate() +16
NHibernate.Cfg.Configuration.BuildSessionFactory() +39
FluentNHibernate.Cfg.FluentConfiguration.BuildSessionFactory() in d:BuildsFluentNHsrcFluentNHibernateCfgFluentConfiguration.cs:93

Anyone had a similar error? I've seach the web / stackoverflow / NHibernate forums but only found people who had a problem when running in medium trust mode, not full trust. I've been developing for several months on this application on this machine with previous versions of Fluent NHibernate and NHibernate.

The machine I'm running this on is 64-bit, you never know that this is relevant.

View 1 Replies

C# - Subsonic Delete With Fluent Query Tool?

Jan 4, 2011

In subsonic 2 we could do this:

public static void DeleteTable(SubSonic.TableSchema.Table table)
{
new Delete().From(table).Execute();
}

How can we do the same thing in v3? I can only seem to find documentation about using generics to target a specific table in the database...I want to be able to use it with a parameter as above.

View 2 Replies

MVC :: DataAnnotations Does Not Work

Jan 18, 2011

I'm building an MVC 2 application with a MySQL database behind it. I've imported the model by adding an ADO.NET Entety Datamodel. Now I want to use DataAnnotations to validate the user input. So I have added the line

[Code]....

[code]....

However, It just doesn't do anything. The Model.IsValid() returns true no matter how long a string I submit.

View 3 Replies

Fluent NHibernate, Dynamically Change Table Of Mapping?

Feb 18, 2010

with fluent nhibernate, is there a way to dynamically switch the table of a mapping at runtime?

public class XYClassMap : ClassMap<XY>
{
public XYClassMap( )
{
Table("XYTable");
Id(d => d.Id).GeneratedBy.Identity();
Map(d => d.Value);
[code]...

View 2 Replies

Using MVC 2, StructureMap, Fluent NHibernate, And PostgreSQL - Finding Tutorials

Aug 8, 2010

I am using the above combo in a new web app Im doing just to try to learn to build new stuff to expand my knowledge. Im hoping to go live if I do a good job.. Im kind of new at MVC and the other products so I was trying to find a link to a good tutorial that set all of these up together.

View 1 Replies

C# - Update Parent Table From Child In Fluent Nhibernate?

Jul 13, 2010

I'm trying to update the data in the parent table that is referenced in the child table from the child's view in Asp.net.

I mapped the tables using Fluent Nhibernate.

In the child table, the mapping looks like this:

[code]....

View 1 Replies

Validate A Single Property With The Fluent Validation Library For .Net

May 17, 2010

Can you validate just a single property with the Fluent Validation Library, and if so how? I thought this discussion thread from January of 2009 showed me how to do it via the following syntax:

validator.Validate(new Person(), x => x.Surname);

Unfortunately it doesn't appear this works in the current version of the library. One other thing that led me to believe that validating a single property might be possible is the following quote from Jeremy Skinners' blog post:

"Finally, I added the ability to be able to execute some of FluentValidation's Property Validators without needing to validate the entire object. This means it is now possible to stop the default "A value was required" message from being added to ModelState. "

However I do not know if that necessarily means it supports just validating a single property or the fact that you can tell the validation library to stop validating after the first validation error.

View 1 Replies

C# - Fluent NHibernate Many-to-many Mapping With Auto-generated Pk Instead Of Composite Key?

Feb 2, 2010

I'm working on a RoleProvider in .NET, using Fluent NHibernate to map tables in an Oracle 9.2 database.

The problem is that the many-to-many table connecting users and roles uses a primary key generated from a sequence, as opposed to a composite key. I can't really change this, because I'm writing it to be implemented in a larger existing system.

Here is my UserMap:

public UserMap()
{
this.Table("USR");[code].....

Yet, this is giving me the error:

Type 'FluentNHibernate.Cfg.FluentConfigurationException' in assembly 'FluentNHibernate, Version=1.0.0.593, Culture=neutral, PublicKeyToken=8aa435e3cb308880' is not marked as serializable.

Is there a simple fix to allow this HasMayToMany to use my PersistentObjectMap extension? I'm thinking I may have to add a convention for this many-to-many relationship, but I don't know where to start with that, since I've just started using NHibernate and Fluent NHibernate only recently.

EDIT: I think I've found a possible solution here: http://marekblotny.blogspot.com/2009/02/fluent-nhbernate-and-collections.html

I'll try the above method of creating an entity and a class map for the linking table and post my findings.

EDIT 2: I created a linking entity as mentioned in the above blog post and downloaded the newest binaries (1.0.0.623).
This helped me discover that the issue was with setting lazy load and trying to add roles to the user object in a completely new session.

I modified the code to move OpenSession to the BeginRequest of an HttpModule as described here. After doing this, I changed my data access code from wrapping the open session in a using statement, which closes the session when it is finished, to getting the current session and wrapping only the transaction in a using statement.

This seems to have resolved the bulk of my issue, but I am now getting an error that says "Could not insert collection" into the USR_ROLE table. And I'm wondering if the above code should work with a UserRoleMap described as:

public UserRoleMap()
{
this.Table("USR_ROLE"); [code]....

Hibernate's documentation for many-to-many relationship suggests creating an object to maintain a one-to-many/many-to-one, as in an ERD. I'm sure this would be much easier with conventional naming standards, but I have to stick with certain abbreviations and odd (and not always properly-implemented) conventions.

View 1 Replies

MVC :: Validating ICollection Using DataAnnotations?

Sep 1, 2010

What's the best way to validate ICollection

ie. sample class:

[code]....

what's the best way to ensure that at least ONE BlogCategory is selected (if on the edit page BlogCategory is a list of checkboxes)

View 2 Replies







Copyrights 2005-15 www.BigResource.com, All rights reserved