ADO.NET :: CTP5 How To Save Related New Objects That Comes From Differents DBContext
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 ?
I have and Article object that I update in my controller.... the object is passed into the controller and then I just call UpdateModel(inArticle) and it was all good. I now expanded my article to belong to a category and want to do that update there as well. I am not sure if it was the right thing to do but just as a start i hard-coded an update to the ArticleCategory table, just after I do the UpdateModel. This works but I am not sure how to code this update?
I am using the repository patter and i somehow feel that I should be passing an Article and an ArticleCategory object from the view to the controller? While I was writing this I thought that I could just extend my article object to include the categoryID but what if I really wanted to pass two un-related objects from the view to the controller? The UpdateModel persistes the database objects as by VoodooMagic, how would it work if I wanted to update 2 un-related objects?
I have a relationship setup between Campaigns table and Urls (FK_Url_Campaign) everything works fine when I try to add a new campaign but when I try to insert a new Url I get:
Entities in 'DatabaseEntity.Url' participate in the 'FK_Url_Campaign' relationship. 0 related 'Campaign' were found. 1 'Campaign' is expected. This is my code: // INSERT public int Insert() { Url dbUrl = new Url(); dbUrl.CampaignId = (int)CampaignId; dbUrl.Url1 = (string)Url; context.AddToUrl(dbUrl); context.SaveChanges(); return (int)dbUrl.UrlId; }
Pretty much i want update/add new campaign and then I call Insert for Url. how would i go about doing this?
I am using Entity Framework for my .NET application. I have been able to return objects and their directly-related objects as well (very convenient), but I am having trouble getting the objects of those objects.
IEnumerable<Lot> i = (((ObjectSet<Car>)_carRepository.GetQuery()) .Include(a => a.CarTypes).Take(10).ToList()
This works and I can access carTypes, however I cannot figure out how to access tables associated with CarTypes (e.g. tables which have fields associated with the car types). I tried to use a Join however I was unable to figure out how to get it to work right.
I'm in a .NET environment and when a user performs a save or update action, Foundation pops up a status message 'processing...' or 'saving...' or 'refreshing...', then 'saved.' After a given amount of time, the message will disappear,sometimes before the given action is really complete. How can I access this functionality and extend the time these status messages appear on the screen?
I want to create two differents DisplayTemplates for the DateTime type, One for Births other for time span:Post (2 minutes ago)Rafael Almeida, 22 years.
I have been design a site it is started nice in explorer but it is not nice I mean it different from IE (borders and alignments) in opera and some other browser. How I can set my site to load by all browser ? I use asp.net to design pages. net framwork 4.0
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.
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; } }
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:
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; } } }
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.
have some Objects, lets say Employee and Role defined as below and I have defined relationships in my database that gives me a list of objects say employees and thanks to my framework each employee object also has a Role object linked via the RoleIDID, UserName, Password, Email, RoleIDRoleID, RoleNameSo in code I can do something like this
I know how to bind a simple objects to a dropdown list. However I am having problems binding my objects which contains sub objects to the control.i.e. with simple object i just do ddl.DataValueField = "myproperty" with my objects they contains sub objects which i want to bind. I have tried ddl.DataValueField = "sub-object.myproperty" which doesnt work.
firstly a static class only ever exists once and is not an instance. Any static members (ie static int NoOfPeople;) is stored in one place and is shared between all sessions (like the old global variables). Now static methods is where i'm not 100% sure. If I have a static method that doesn't use any other static members could this cause inconstant results, example (this is a fairly pointless method but just a quick example of the top of my head)
[Code]....
So in this example if two sessions (or threads) were to call this at the same time - would they both get back the expected results, because the method only uses private data (a, b and totalToReturn).Im sure this sounds a little simple but I will be using static methods to build user objects and various other objects that there will have to be a 100% garentee that the objects will not get mixed up between sessions and the wrong things return to the user.
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.
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?
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 }
I'm working on a project in which we have a database, data layer (entity framework), business layer and web/UI layer.I want to use ASP.NET Dynamic Data for the web layer, but don't want it to access the data layer or database, as I want it to be purely running off business logic, and not directly accessing the data.However, it appears that Dynamic Data only allows Linq-to-SQL or entity framework data sources to be used.Has anyone used it with business-layer objects instead?
Lets say I am doing a shoping cart. I authenticate the user with a session variable.For example:
If(Request.IsAuthenticated) // Here I want to add to the shoping cart. // Can I do the following Session["Cart"] = "Washing Machine"; Now will this Session["Cart"] value which is washing machine here be unique to diff customers?