C# - CTP5 EF Code / Getting Error
Mar 6, 2011
You can find the source code demonstrating this issue @ http://code.google.com/p/contactsctp5/
I have three model objects. Contact,ContactInfo,ContactInfoType. Where a contact has many contactinfo's and each contactinfo is a contactinfotype. Fairly simple I guess. The problem I'm running into is when I go to edit the contact object. I pulled it from my contact repository. Then I run "UpdateModel(contact);" and it updates the object with all the values from my form. (monitoring with debug) When I save the changes though, I get the following error:
The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.
It seems like after I call update model it nulls out my references and this seems to break everything?
Here are my models:
public partial class Contact {
public Contact() {
this.ContactInformation = new HashSet<ContactInformation>();
}
public int ContactId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<ContactInformation> ContactInformation { get; set; }
}
public partial class ContactInformation {
public int ContactInformationId { get; set; }
public int ContactId { get; set; }
public int ContactInfoTypeId { get; set; }
public string Information { get; set; }
public virtual Contact Contact { get; set; }
public virtual ContactInfoType ContactInfoType { get; set; }
}
public partial class ContactInfoType {
public ContactInfoType() {
this.ContactInformation = new HashSet<ContactInformation>();
}
public int ContactInfoTypeId { get; set; }
public string Type { get; set; }
public virtual ICollection<ContactInformation> ContactInformation { get; set; }
}
My Controller Action:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Contact person) {
if (this.ModelState.IsValid) {
var contact = this.contactRepository.GetById(person.ContactId);
UpdateModel(contact);
this.contactRepository.Save();
TempData["message"] = "Contact Saved.";
return PartialView("Details", contact);
} else {
return PartialView(person);
}
}
Context Code:
protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder) {
modelBuilder.Entity<Contact>()
.HasMany(c => c.ContactInformation)
.WithRequired()
.HasForeignKey(c => c.ContactId);
modelBuilder.Entity<ContactInfoType>()
.HasMany(c => c.ContactInformation)
.WithRequired()
.HasForeignKey(c => c.ContactInfoTypeId);
}
View 2 Replies
Similar Messages:
Jan 3, 2011
I have the following classes:
public class Category
{
public int CategoryId { get; set; }
public string Name { get; set; }
}
public partial class CategoryMap : EntityTypeConfiguration<Category>
{
public CategoryMap()
{
this.HasKey(c => c.CategoryId);
this.Property(c => c.Name).IsRequired().HasMaxLength(400);
}
}
public class MyObjectContext : DbContext
{
public MyObjectContext(string connectionStringName)
: base(connectionStringName)
{
}
public DbSet<Category> Categories { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new CategoryMap());
base.OnModelCreating(modelBuilder);
}
}
Now when I run the following code I get an exception (GenericArguments[0], 'System.Int32', on 'System.Data.Entity.Internal.Linq.ReplacementDbQueryWrapper`1[TEntity]' violates the constraint of type 'TEntity')
DbDatabase.SetInitializer<MyObjectContext>(new DropCreateDatabaseIfModelChanges<MyObjectContext>());
using (var context = new MyObjectContext("NopSqlConnection"))
{
var query1 = from c in context.Categories
select c.CategoryId;
var test1 = query1.ToList(); //works fine
var query2 = from c in context.Categories
where query1.Contains(c.CategoryId)
orderby c.Name descending
select c;
var test2 = query2.ToList(); //throws the exception
}
View 1 Replies
Jan 22, 2011
I've been using EF as my primary ORM for quiet some time now. Today I decided to use EF Code First to create my model for my new project. So I went ahead and read a bunch of documents on MSDN and some blog posts by Scott Guthrie and others. Unfortunately, what I've read does not go beyond the basics of using Code First within an ASP.NET MVC application. But as you might know, in real-world applications the structure of the solution is a little different. Anyway, to make a long story short:
- I created all the POCO files that will be needed.
- I created the SharweEntities class which extends the DbContext class.
- I added the following connection string to my Web.config file
[Code]....
Then I started the application and checked whether a new database was created inside SQL Server 2008 Express, but found nothing. I'm not sure what's wrong but I suspect it might be the way I'm structuring my solution? Here's the structure:
- Sharwe.MVC : The ASP.NET MVC3 Web Application (has nothing except a HomeController and a corresponding simple view at the time being)
- Sharwe.Data : model class and data access logic (contains all the POCO classes and the SharweEntities class)
- Sharwe.Services : Business logic
Here's an image that shows the structure of my solution:
View 3 Replies
Mar 7, 2011
I am hoping that people are not going to think it is too simple to bother with, because I am beyond stressed here..
I am trying to display a grid of Articles and their types using:
ASP.NET MVC 3
EF Code First CTP 5
The grid needs to look something like this:
TITLE TYPE
Roses Flower
Tables Furniture
what I need to change/add to the following
[Code]....
View 1 Replies
Jan 18, 2011
Im a fan of the EF code first and with its last preview of the CTP5 I wonder if it would be safe for me to use this for a smaller site for customer? I would love to get your opinions on this? And any good sources for tutorials and information would be sweet. I'm currently reading the post on scottgu's blog about it.
View 1 Replies
Jan 4, 2011
I have two entities (Customer and CustomerRole) and would like to declare many-to-many relationship between them. I can do using the following code:
modelBuilder.Entity<CustomerRole>()
.HasMany(cr => cr.Customers)
.WithMany(c => c.CustomerRoles)
.Map(m => m.ToTable("Customer_CustomerRole_Mapping"));
But it creates the relationship (and the third mapping table) with cascade delete switched off by default. How can I tell EF to create the relationship with cascade delete switched on when using many-to-many?
View 1 Replies
Feb 28, 2011
I wonder if its safe to use the CTP5 in production yet. My main use would be for 2 small projects. I Know they pre released it but any thoughts on this if it would hold up for production are welcome.
View 1 Replies
Feb 3, 2011
I have a problem with strange generate sql in ef4 ctp5. I have simple model with mapping :
[Table("post_auction")]
public class PostAuction
{
[Key,Column(Name="Id"),DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGenerationOption.Identity)]
public int Id { get; set; }
[Column(Name = "Number")]
public int Number { get; set; }
[Column(Name = "Label")]
public string Label { get; set; }
[Column(Name = "Description")]
public string Description { get; set; }
[Column(Name = "CategoryId")]
public int PostAuctionCategoryId { get; set; }
[Column(Name = "PriceCZK")]
public int PriceCZK { get; set; }
[NotMapped]
public bool IsAuctionPhotoExitst
{
get
{
if (File.Exists(HttpContext.Current.Server.MapPath("~/Public/Images/Posts/Thumbs/small_" + this.Number + ".jpg")))
return true;
return false;
}
}
}
and my linq query is :...............
View 2 Replies
Mar 4, 2011
I am having a strange problem with using stored proc in CTP5.I am calling a stored proc in my function like this:
private List<Test> GetDatat(Test pTest)
{
using(var staticDB=new StaticDB()) [code]...
But I am getting error that parameters not found. Looking at the sql trace I can see that CTP5 is sending "default" value if any of my parameters is null instead of the null value.
View 2 Replies
Mar 3, 2011
I'm working on a MVC3 application and I created my POCO classes from my database with the DbContext Code Generator. All goes fine until I got stuck in this situation. Note that I use the repository pattern and I use for every entity a dedicated repository that every get a new instance of the DbContext.
Now, I'm in this situation:
object A has a relation one-to-many with B (A can have one or many B)
object B has a relation many-to-one with C (C can have one or many B)
object B has a relation many-to-one with D (D can have one or many B)
I should add a new object B, consider that object C and D are yet existing, so I must only do the relation and the object A can be created or updated. In the specific consider that A is customer and B is subscriptions (C and D are virtual objects properties
in the B).Now If I try to save I got duplicates in C and D tables, while the management of the object seems to work.
Here's the code: [Code]....
And here the add and the save method of the customer repository: [Code]....
Should I check for every relation and modify the state of the entry to Unchanged or something like that ?
View 1 Replies
Jun 6, 2010
Error:
Executed as user: MACSTEELUSA.COMsa. ...9.00.3042.00 for 32-bit Copyright (C) Microsoft Corp 1984-2005. All rights reserved. Started: 8:00:17 PM Error: 2010-06-02 20:00:18.56 Code: 0xC0202009 Source: CRM_ORACLE_ARSUMMARY Connection manager "SourceConnectionOLEDB" Description: SSIS Error Code DTS_E_OLEDBERROR. An OLE DB error has occurred. Error code: 0x80004005. An OLE DB record is available. Source: "Microsoft OLE DB Provider for Oracle" Hresult: 0x80004005 Description: "Oracle client
and networking components were not found. These components are supplied by Oracle Corporation and are part of the Oracle Version 7.3.3 or later client software installation. Provider is unable to function until these components are installed.". End Error Error: 2010-06-02 20:00:18.58 Code: 0xC020801C Source: Data Flow Task Source - Query [1] Description: SSIS Error Code DTS_E_CANNOTACQUIRECONNECTIONFROMCONNECTIONMANAGER. The AcquireCon... The package execution fa... The step failed.
Tasks Taken:Went to this folder checked for tnsnames.ora file but it is in good shape.
C:ORACLEproduct11.2.0client_1
etworkadmin
View 2 Replies
Dec 6, 2010
I have a serious problem with "Error on Page". The error message points to line number 939, char 13. In my code behind (C#) in line number 939 is only an obsolete method found which is no longer called. The aspx file has only 339 lines. What the heck is line number 939?The Webapplication allows a special user group to change some group memberships for members of another user group in Active Directory. The App handles 3internal DataViews derived from corresponding DataTables as DataSource for 3 GridViews and some other internal lists with objects (List<obj>).
It uses windows authentication to get current users credentials and his membership in the "Operators" group. This credentials will be passed-through to allow the process managing group memberships in active directory.After starting the App in browser it seems to work fine. But after an indeterminated time it doesn't longer respond. After each click on buttons (or link buttons) you only can see the message "Error on Page" in the browsers status bar below.I played with session timeout, storing the DataTables in session variables, without success.
Last week I found this article here: [URL]" and I addedEnableEventValidation="false" ViewStateEncryptionMode="Never"
to Page declaration. However, at some point the the server does not respond. Each time the worker process on webserver recycles it seems the application turn to wrong state. Might be important: All controls including GridViews are embedded in an AJAX UpdatePanel. How to get a better error message? Debugging is enabled and Custom Error handling On, Off or Remote Only brings the same result as described.
View 3 Replies
Jun 28, 2010
I have got a problem tesing paypal sandbox IPN. i have got this error message: IPN delivery failed. HTTP error code 500: Internal Server Error
I could not find out what this error means.
View 1 Replies
Aug 7, 2010
I have hosted a service in the IIS server, while consuming the service i am getting some error. I have mentioned the error code below.
Error code:
Server Error in '/' Application.
The type 'EchoTunnelService.EchoService', provided as the Service attribute value in the ServiceHost directive could not be found.
Description:An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: The type 'EchoTunnelService.EchoService', provided as the Service attribute value in the ServiceHost directive could not be found.
Source Error: [Code]....
Version Information: Microsoft .NET Framework Version:2.0.50727.3607; ASP.NET Version:2.0.50727.3614
View 1 Replies
Jan 19, 2011
Web service error response (code/message etc) would you store it in a database? or would you keep the error response in a method.By the time I'm done with this, there will be hundreds of error response, maybe in the future, thousands? (I dont know yet, depends how large this web service grows).EDIT: error response is the response returned back to the application via the web service, (not to be confused with error logging).
View 1 Replies
Mar 2, 2010
Not sure why the below stated error occurs when tried to access the user details in LDAP from .Net application.
'ADSDSOOBJECT' failed with no error message available, result code: DB_SEC_E_PERMISSIONDENIED(0x80040E09)
View 1 Replies
May 9, 2010
Code:
01.If InStr( Request.ServerVariables("HTTP_REFERER"), "google") > 0 Then
KeyURL = Request.ServerVariables("HTTP_REFERER")
' Remove all up to q=
KeyLen = Len(KeyURL)
kStart = InStr( KeyURL, "q=" )
kStart = kStart + 1
KeyRight = KeyLen - kStart
Keyword = Right( keyURL, KeyRight )
[code]...
View 4 Replies
Sep 18, 2010
I get the dreaded "the compiler failed with error code 1" error message when application starts. Sometimes, it does not even start and in VS 2008 I get:"Could not load file or assembly 'file///C:WindowsMicrosoft.NetFrameworv2.0.50727Temporary ASP.NET FilesInternal2d7d8a83649918fApp_Web_timecard.aspx.3ecd542a.aa9wycbd.dll' or one of its dependencies. The system cnnot find teh file specified"I have searched for this error and tried everything suggested to no avail. I deleted the "Internal" folder in Temporary ASP.NET Files folder, changed something in one of teh file and also in web.config to force a recompile and restared IIS. Same thing happens. I checked all the files and do not a circular definition/referencing.
View 2 Replies
Oct 27, 2010
I have written the following code in my web application to start the sql Job
[code]....
what could be the cause of this error. The same code and same ddl its running great in my local PC but it is erroring out when the website is deployed to the web server.
View 3 Replies
Dec 2, 2010
I have a form that the users fill out and submit, sometimes there is an error and I need to delete the submitted data from the
database before the user resubmits. So I want to run some code when the error fires, how can i do this?
View 2 Replies
Mar 29, 2010
EDIT ~ Updated the title and the question body: This is the edit. I want this behavior per-app on IIS6/7. I asked it initially before we migrated to IIS7, so any answer can be altered between the two (I've learned a bit about IIS7 since then ;] ) but I am looking for an answer that does work. I need to redirect per-app not per-server based on the user canceling 401 Auth request (meaning 401.1 error code). On IIS6, using NTLM Authentication (meaning Integrated Windows Authentication) if the user cancels the authentication request, how can I redirect them to another page? I can't just grab 401 (tried) or 401.1 (not an int) in the web.config.
I can't redirect if the issue is a 401 status because I'm intentionally pushing for a 401 to get the response, yeah? So how do I capture when they canceled on the browser challenge? To confirm that I'm being clear: If I open firefox and navigate to a IWA page, it shows me a dialog (assuming I haven't configured that away in about:config) and I key in the windows credentials to use. I want to prevent them stopping that box.
View 1 Replies
May 2, 2010
I have an execute insert mmethod in my code behind page to trigger an insert on a database, which the button click event for the insertion calls. However I get this error when clicking on the "submit" button when I run the application:
Index was outside the bounds of the array.Here's my code for this code behind page. The line of code highlighted in bold is where this error message points to.
[Code]....
View 3 Replies
Mar 15, 2011
I created an ASHX file and use it to handle async file uploads.Since the site might not be hosted on our servers, I want to check for write permissions and delete permissions and supply the end user (site content editor in this case) with an error they can deal with.
Im using uploadify for the upload, Im not sure, but I`m guessing this complicates the return of a message that can be shown on the page, but maybe not.
View 2 Replies
Jul 8, 2010
I have a application in asp.net2.0 with C#. I have migrated my application in .NET 3.5 & I am receiving the below error.
Could not load file or assembly 'Microsoft.Build.Framework' or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.
View 1 Replies
Nov 15, 2010
I am using Visual studio 2010, oracle 10g, Windows server 2008 (64 bit).
I am gettign followign error message when trying to verify datasource of crystal report from visula studio.
Steps. open report -> fields explore -> right click -> Verify datasoucrce -
> select data source, enter userid & password.
showig error message
Logon failed.
Details: ADO Error Code: 0x80004005
Source: Microsoft OLE DB Provider for Oracle
Description: Oracle client and networking components were not found. These components are supplied by Oracle Corporation and are part of the Oracle Version 7.3.3 or later client software installation.
Provider is unable to function until these components are installed.
View 1 Replies