Search Results

Search found 9916 results on 397 pages for 'entity component'.

Page 31/397 | < Previous Page | 27 28 29 30 31 32 33 34 35 36 37 38  | Next Page >

  • Dynamic Components

    - by Alex
    I am attempting to design a component-based architecture that allows Components to be dynamically enabled and disabled, much like the system employed by Unity3D. For example, all Components are implicitly enabled by default; however, if one desires to halt execution of code for a particular Component, one can disable it. Naively, I want to have a boolean flag in Component (which is an abstract class), and somehow serialize all method calls into strings, so that some sort of ComponentManager can check if a given Component is enabled/disabled before processing a method call on it. However, this is a pretty bad solution. I feel like I should employ some variation of the state paradigm, but I have yet to make progress. Any help would be greatly appreciated,

    Read the article

  • Different Approaches of Entity Framework

    Entity Framework provides three different approaches to deal with the model, and each one has its own pros and cons. Ambily Kavumkal Kamalasanan discusses the advantages of the Model, Database, and Code First approaches to modeling in Entity Framework 5.0. Entity Framework still has its share of issues and is not widely accepted yet - but through contributing to its ongoing development the community can make it more stable and increase its adoption.

    Read the article

  • Inheritance with POCO entities in Entity Framework 4

    - by Juvaly
    Hi All, I have a Consumer class and a BillableConsumer : Consumer class. When trying to do any operation on my "Consumers" set, I get the error message "Object mapping could not be found for Type with identity Models.BillableConsumer. From the CSDL: <EntityType Name="BillableConsumer" BaseType="Models.Consumer"> <Property Type="String" Name="CardExpiratoin" Nullable="false" /> <Property Type="String" Name="CardNumber" Nullable="false" /> <Property Type="String" Name="City" Nullable="false" /> <Property Type="String" Name="Country" Nullable="false" /> <Property Type="String" Name="CVV" Nullable="false" /> <Property Type="String" Name="NameOnCard" Nullable="false" /> <Property Type="String" Name="PostalCode" Nullable="false" /> <Property Type="String" Name="State" /> <Property Type="String" Name="StreetAddress" Nullable="false" /> </EntityType> From the C-S: <EntitySetMapping Name="Consumers"> <EntityTypeMapping TypeName="IsTypeOf(Models.Consumer)"> <MappingFragment StoreEntitySet="consumer"> <ScalarProperty Name="LoginID" ColumnName="LoginID" /> <ScalarProperty Name="FirstName" ColumnName="FirstName" /> <ScalarProperty Name="LastName" ColumnName="LastName" /> </MappingFragment> </EntityTypeMapping> <EntityTypeMapping TypeName="IsTypeOf(Models.BillableConsumer)"> <MappingFragment StoreEntitySet="billinginformation"> <ScalarProperty Name="CardExpiratoin" ColumnName="CardExpiratoin" /> <ScalarProperty Name="CardNumber" ColumnName="CardNumber" /> <ScalarProperty Name="City" ColumnName="City" /> <ScalarProperty Name="Country" ColumnName="Country" /> <ScalarProperty Name="CVV" ColumnName="CVV" /> <ScalarProperty Name="LoginID" ColumnName="LoginID" /> <ScalarProperty Name="NameOnCard" ColumnName="NameOnCard" /> <ScalarProperty Name="PostalCode" ColumnName="PostalCode" /> <ScalarProperty Name="State" ColumnName="State" /> <ScalarProperty Name="StreetAddress" ColumnName="StreetAddress" /> </MappingFragment> </EntityTypeMapping> </EntitySetMapping> Is this because I did not specifically add the BillableConsumer entity to the object set? How do I do that in a POCO scenario? Thanks! UPDATE: I decided to test whether or not POCOs generated with the T4 template would solve the problem and they did. The most annoying part is that when I restored my original classes from SVN to try and figure out how they are different - they worked as well!! Not adding this as an answer because someone else might have an actual explanation...

    Read the article

  • Defining an Entity Framework 1:1 association

    - by Craig Fisher
    I'm trying to define a 1:1 association between two entities (one maps to a table and the other to a view - using DefinedQuery) in an Entity Framework model. When trying to define the mapping for this in the designer, it makes me choose the (1) table or view to map the association to. What am I supposed to choose? I can choose either of the two tables but then I am forced to choose a column from that table (or view) for each end of the relationship. I would expect to be able to choose a column from one table for one end of the association and a column from the other table for the other end of the association, but there's no way to do this. Here I've chosen to map to the "DW_ WF_ClaimInfo" view and it is forcing me to choose two columns from that view - one for each end of the relationship. I've also tried defining the mapping manually in the XML as follows: <AssociationSetMapping Name="Entity1Entity2" TypeName="ClaimsModel.Entity1Entity2" StoreEntitySet="Entity1"> <EndProperty Name="Entity2"> <ScalarProperty Name="DOCUMENT" ColumnName="DOCUMENT" /> </EndProperty> <EndProperty Name="Entity1"> <ScalarProperty Name="PK_DocumentId" ColumnName="PK_DocumentId" /> </EndProperty> </AssociationSetMapping> But this gives: Error 2010: The Column 'DOCUMENT' specified as part of this MSL does not exist in MetadataWorkspace. Seems like it still expects both columns to come from the same table, which doesn't make sense to me. Furthermore, if I select the same key for each end, e.g.: <AssociationSetMapping Name="Entity1Entity2" TypeName="ClaimsModel.Entity1Entity2" StoreEntitySet="Entity1"> <EndProperty Name="Entity2"> <ScalarProperty Name="DOCUMENT" ColumnName="PK_DocumentId" /> </EndProperty> <EndProperty Name="Entity1"> <ScalarProperty Name="PK_DocumentId" ColumnName="PK_DocumentId" /> </EndProperty> </AssociationSetMapping> I then get: Error 3021: Problem in Mapping Fragment starting at line 675: Each of the following columns in table AssignedClaims is mapped to multiple conceptual side properties: AssignedClaims.PK_DocumentId is mapped to <AssignedClaimDW_WF_ClaimInfo.DW_WF_ClaimInfo.DOCUMENT, AssignedClaimDW_WF_ClaimInfo.AssignedClaim.PK_DocumentId> What am I not getting?

    Read the article

  • Retrieving/Updating Entity Framework POCO objects that already exist in the ObjectContext

    - by jslatts
    I have a project using Entity Framework 4.0 with POCOs (data is stored in SQL DB, lazyloading is enabled) as follows: public class ParentObject { public int ID {get; set;} public virtual List<ChildObject> children {get; set;} } public class ChildObject { public int ID {get; set;} public int ChildRoleID {get; set;} public int ParentID {get; set;} public virtual ParentObject Parent {get; set;} public virtual ChildRoleObject ChildRole {get; set;} } public class ChildRoleObject { public int ID {get; set;} public string Name {get; set;} public virtual List<ChildObject> children {get; set;} } I want to create a new ChildObject, assign it a role, then add it to an existing ParentObject. Afterwards, I want to send the new ChildObject to the caller. The code below works fine until it tries to get the object back from the database. The newChildObjectInstance only has the ChildRoleID set and does not contain a reference to the actual ChildRole object. I try and pull the new instance back out of the database in order to populate the ChildRole property. Unfortunately, in this case, instead of creating a new instance of ChildObject and assigning it to retreivedChildObject, EF finds the existing ChildObject in the context and returns the in-memory instance, with a null ChildRole property. public ChildObject CreateNewChild(int id, int roleID) { SomeObjectContext myRepository = new SomeObjectContext(); ParentObject parentObjectInstance = myRepository.GetParentObject(id); ChildObject newChildObjectInstance = new ChildObject() { ParentObject = parentObjectInstance, ParentID = parentObjectInstance.ID, ChildRoleID = roleID }; parentObjectInstance.children.Add(newChildObjectInstance); myRepository.Save(); ChildObject retreivedChildObject = myRepository.GetChildObject(newChildObjectInstance.ID); string assignedRoleName = retreivedChildObject.ChildRole.Name; //Throws exception, ChildRole is null return retreivedChildObject; } I have tried setting MergeOptions to Overwrite, calling ObjectContext.Refresh() and ObjectContext.DetectChanges() to no avail... I suspect this is related to the proxy objects that EF injects when working with POCOs. Has anyone run into this issue before? If so, what was the solution?

    Read the article

  • .Net Entity Framework SaveChanges is adding without add method

    - by tmfkmoney
    I'm new to the entity framework and I'm really confused about how savechanges works. There's probably a lot of code in my example which could be improved, but here's the problem I'm having. The user enters a bunch of picks. I make sure the user hasn't already entered those picks. Then I add the picks to the database. var db = new myModel() var predictionArray = ticker.Substring(1).Split(','); // Get rid of the initial comma. var user = Membership.GetUser(); var userId = Convert.ToInt32(user.ProviderUserKey); // Get the member with all his predictions for today. var memberQuery = (from member in db.Members where member.user_id == userId select new { member, predictions = from p in member.Predictions where p.start_date == null select p }).First(); // Load all the company ids. foreach (var prediction in memberQuery.predictions) { prediction.CompanyReference.Load(); } var picks = from prediction in predictionArray let data = prediction.Split(':') let companyTicker = data[0] where !(from i in memberQuery.predictions select i.Company.ticker).Contains(companyTicker) select new Prediction { Member = memberQuery.member, Company = db.Companies.Where(c => c.ticker == companyTicker).First(), is_up = data[1] == "up", // This turns up and down into true and false. }; // Save the records to the database. // HERE'S THE PART I DON'T UNDERSTAND. // This saves the records, even though I don't have db.AddToPredictions(pick) foreach (var pick in picks) { db.SaveChanges(); } // This does not save records when the db.SaveChanges outside of a loop of picks. db.SaveChanges(); foreach (var pick in picks) { } // This saves records, but it will insert all the picks exactly once no matter how many picks you have. //The fact you're skipping a pick makes no difference in what gets inserted. var counter = 1; foreach (var pick in picks) { if (counter == 2) { db.SaveChanges(); } counter++; } There's obviously something going on with the context I don't understand. I'm guessing I've somehow loaded my new picks as pending changes, but even if that's true I don't understand I have to loop over them to save changes. Can someone explain this to me?

    Read the article

  • Entity framework 4 many-to-many insertion?

    - by Saxman
    Hi all, I'm not very familiar with the many-to-many insertion process using Entity Framework 4, POCO. I have a blog with 3 tables: Post, Comment, and Tag. A Post can have many Tags and a Tag can be in many Posts. Here are the Post and Tag models: public class Tag { public int Id { get; set; } [Required] [StringLength(25, ErrorMessage = "Tag name can't exceed 25 characters.")] public string Name { get; set; } public virtual ICollection<Post> Posts { get; set; } } public class Post { public int Id { get; set; } [Required] [StringLength(512, ErrorMessage = "Title can't exceed 512 characters")] public string Title { get; set; } [Required] [AllowHtml] public string Content { get; set; } public string FriendlyUrl { get; set; } public DateTime PostedDate { get; set; } public bool IsActive { get; set; } public virtual ICollection<Comment> Comments { get; set; } public virtual ICollection<Tag> Tags { get; set; } } Now when I'm adding a new post, I'm not sure what would be the right way to do. I'm thinking that I'll have a textbox where I can select multiple tags for that post (this part is already done), in my controller, I will check to see if the tag is already exists or not, if not, then I will insert the new tag. But I'm not even sure based on the models that I've created for EF, will they create a PostsTags table, or they are creating just a Tags and a Posts table and links between the two? How would I insert the new Post and set the tags to that post? Is it just newPost.Tags = Tags (where Tags are the one that got selected, do I even need to check to see if they already exists?), and then something like _post.Add(newPost);? Thanks.

    Read the article

  • Entity Framework: An object with the same key already exists in the objectstatemanager

    - by NealR
    I see that this question has been asked a lot, however I haven't found anything yet that solves the problem I'm having. Obviously i'm using the Entity Framework to perform an update to a record. Once the updates are complete, however, whenever I try to save I get the following error message: An object with the same key already exists in the objectstatemanager At first I was passing in a collection object from the view that contained a copy of the the ZipCodeTerritory model object zipToUpdate. I changed the code by pulling this object out and just sending in the relevant fields instead. However, I'm still getting the same error. What's also weird is the first time I run this code, it works fine. Any attempt after that I get the error. Controller Here is the code from the method calling the edit function public static string DescriptionOnly(ZipCodeIndex updateZip) { if (!string.IsNullOrWhiteSpace(updateZip.newEffectiveDate) || !string.IsNullOrWhiteSpace(updateZip.newEndDate)) { return "Neither effective or end date can be present if updating Territory Code only; "; } _updated = 0; foreach (var zipCode in updateZip.displayForPaging.Where(x => x.Update)) { ProcessAllChanges(zipCode, updateZip.newTerritory, updateZip.newStateCode, updateZip.newDescription, updateZip.newChannelCode); } _msg += _updated + " record(s) updated; "; return _msg; } And here is the method that actually does the updating. private static void ProcessAllChanges(ZipCodeTerritory zipToUpdate, string newTerritory, string newStateCode, string newDescription, string newChannelCode) { try { if (!string.IsNullOrWhiteSpace(newTerritory)) zipToUpdate.IndDistrnId = newTerritory; if (!string.IsNullOrWhiteSpace(newStateCode)) zipToUpdate.StateCode = newStateCode; if (!string.IsNullOrWhiteSpace(newDescription)) zipToUpdate.DrmTerrDesc = newDescription; if (!string.IsNullOrWhiteSpace(newChannelCode)) zipToUpdate.ChannelCode = newChannelCode; if (zipToUpdate.EndDate == DateTime.MinValue) zipToUpdate.EndDate = DateTime.MaxValue; _db.Entry(zipToUpdate).State = EntityState.Modified; _db.SaveChanges(); _updated++; } catch (DbEntityValidationException dbEx) { _msg += "Error during update; "; EventLog.WriteEntry("Monet", "Error during ProcessAllChanges: " + zipToUpdate.ToString() + " |EX| " + dbEx.Message); } catch (Exception ex) { _msg += "Error during update; "; EventLog.WriteEntry("Monet", "Error during ProcessAllChanges: " + zipToUpdate.ToString() + " |MESSAGE| " + ex.Message); } } EDIT The ZipCodeIndex object contains a list of ZipCodeTerritory model objects. These aren't being pulled from a linq query, but instead simply passed back to the controller from the view. Here is the signature of the controller method that starts the process: [HttpPost] public ActionResult Update(ZipCodeIndex updateZip, string button)

    Read the article

  • T-4 Templates for ASP.NET Web Form Databound Control Friendly Logical Layers

    - by joycsharp
    I just released an open source project at codeplex, which includes a set of T-4 templates to enable you to build logical layers (i.e. DAL/BLL) with just few clicks! The logical layers implemented here are  based on Entity Framework 4.0, ASP.NET Web Form Data Bound control friendly and fully unit testable. In this open source project you will get Entity Framework 4.0 based T-4 templates for following types of logical layers: Data Access Layer: Entity Framework 4.0 provides excellent ORM data access layer. It also includes support for T-4 templates, as built-in code generation strategy in Visual Studio 2010, where we can customize default structure of data access layer based on Entity Framework. default structure of data access layer has been enhanced to get support for mock testing in Entity Framework 4.0 object model. Business Logic Layer: ASP.NET web form based data bound control friendly business logic layer, which will enable you few clicks to build data bound web applications on top of ASP.NET Web Form and Entity Framework 4.0 quickly with great support of mock testing. Download it to make your web development productive. Enjoy!

    Read the article

  • Getting code-first Entity Framework to build tables on SQL Azure

    - by NER1808
    I am new the code-first Entity Framework. I have tried a few things now, but can't get EF to construct any tables in the my SQL Azure database. Can anyone advise of some steps and settings I should check. The membership provider has no problems create it's tables. I have added the PersistSecurityInfo=True in the connection string. The connection string is using the main user account for the server. When I implement the tables in the database using sql everything works fine. I have the following in the WebRole.cs //Initialize the database Database.SetInitializer<ReykerSCPContext>(new DbInitializer()); My DbInitializer (which does not get run before I get a "Invalid object name 'dbo.ClientAccountIFAs'." when I try to access the table for the first time. Sometime after startup. public class DbInitializer:DropCreateDatabaseIfModelChanges<ReykerSCPContext> { protected override void Seed(ReykerSCPContext context) { using (context) { //Add Doc Types context.DocTypes.Add(new DocType() { DocTypeId = 1, Description = "Statement" }); context.DocTypes.Add(new DocType() { DocTypeId = 2, Description = "Contract note" }); context.DocTypes.Add(new DocType() { DocTypeId = 3, Description = "Notification" }); context.DocTypes.Add(new DocType() { DocTypeId = 4, Description = "Invoice" }); context.DocTypes.Add(new DocType() { DocTypeId = 5, Description = "Document" }); context.DocTypes.Add(new DocType() { DocTypeId = 6, Description = "Newsletter" }); context.DocTypes.Add(new DocType() { DocTypeId = 7, Description = "Terms and Conditions" }); //Add ReykerAccounttypes context.ReykerAccountTypes.Add(new ReykerAccountType() { ReykerAccountTypeID = 1, Description = "ISA" }); context.ReykerAccountTypes.Add(new ReykerAccountType() { ReykerAccountTypeID = 2, Description = "Trading" }); context.ReykerAccountTypes.Add(new ReykerAccountType() { ReykerAccountTypeID = 3, Description = "SIPP" }); context.ReykerAccountTypes.Add(new ReykerAccountType() { ReykerAccountTypeID = 4, Description = "CTF" }); context.ReykerAccountTypes.Add(new ReykerAccountType() { ReykerAccountTypeID = 5, Description = "JISA" }); context.ReykerAccountTypes.Add(new ReykerAccountType() { ReykerAccountTypeID = 6, Description = "Direct" }); context.ReykerAccountTypes.Add(new ReykerAccountType() { ReykerAccountTypeID = 7, Description = "ISA & Direct" }); //Save the changes context.SaveChanges(); } and my DBContext class looks like public class ReykerSCPContext : DbContext { //set the connection explicitly public ReykerSCPContext():base("ReykerSCPContext"){} //define tables public DbSet<ClientAccountIFA> ClientAccountIFAs { get; set; } public DbSet<Document> Documents { get; set; } public DbSet<DocType> DocTypes { get; set; } public DbSet<ReykerAccountType> ReykerAccountTypes { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { //Runs when creating the model. Can use to define special relationships, such as many-to-many. } The code used to access the is public List<ClientAccountIFA> GetAllClientAccountIFAs() { using (DataContext) { var caiCollection = from c in DataContext.ClientAccountIFAs select c; return caiCollection.ToList(); } } and it errors on the last line. Help!

    Read the article

  • Correct way to edit and update complex viewmodel objects using asp.net-mvc2 and entity framework

    - by jslatts
    I have a table in my database with a one to many relationship to another table: ParentObject ID Name Description ChildObject ID Name Description ParentObjectID AnotherObjectID The objects are mapped into Entity Framework and exposed through a data access class. It seemed like ViewModels are recommended when the data to be displayed greatly differs from the domain object, so I created a ViewModel as follows: public class ViewModel { public IList<ParentObject> ParentObjects { get; set; } public ParentObject selectedObject { get; set; } public IList<ChildObject> ChildObjects { get; set; } } I have a view that displays a list of ParentObjects and when clicked will allow a ChildObject to be modified saved. <% using (Html.BeginForm()) { %> <table> <% foreach (var parent in Model.ParentObjects) { %> <tr> <td> ObjectID [<%= Html.Encode(parent.ID)%>] </td> <td> <%= Html.Encode(parent.Name)%> </td> <td> <%= Html.Encode(parent.Description)%> </td> </tr> <% } %> </table> <% if (Model.ParentObject != null) { %> <div> Name:<br /> <%= Html.TextBoxFor(model => model.ParentObject.Name) %> <%= Html.ValidationMessageFor(model => model.ParentObject.Name, "*")%> </div> <div> Description:<br /> <%= Html.TextBoxFor(model => model.ParentObject.Description) %> <%= Html.ValidationMessageFor(model => model.ParentObject.Description, "*")%> </div> <div> Child Objects </div> <% for (int i = 0; i < Model.ParentObject.ChildObjects.Count(); i++) { %> <div> <%= Html.DisplayTextFor(sd => sd.ChildObjects[i].Name) %> </div> <div> <%= Html.HiddenFor(sd => sd.ChildObjects[i].ID )%> <%= Html.TextBoxFor( sd => sd.ChildObjects[i].Description) %> <%= Html.ValidationMessageFor(sd => sd.ChildObjects[i].Description, "*") %> </div> <% } } } %> This all works fine. My question is around the best way to update the EF objects and persist the changes back to the database. I initially tried: [HttpPost] public ActionResult Edit(ViewModel viewModel) { ParentObject parent = myRepository.GetParentObjectByID(viewModel.SelectedObject.ID); if ((!ModelState.IsValid) || !TryUpdateModel(parent, "SelectedObject", new[] { "Name", "Description" })) { || !TryUpdateModel(parent.ChildObjects, "ChildObjects", new[] { "Name", "Description" })) { //Code to handle failure and return the current model snipped return View(viewModel); } myRepository.Save(); return RedirectToAction("Edit"); } When I try to save a change to the child object, I get this exception: Entities in 'MyEntities.ChildObject' participate in the 'FK_ChildObject_AnotherObject' relationship. 0 related 'AnotherObject' were found. 1 'AnotherObject' is expected. Investigation on StackOverflow and generally googling led me to this blog post that seems to describe my problem: TryUpdateModel() does not correctly handle nested collections. Apparently, (and stepping through the debugger confirms this) it creates a new ChildObject instead of associating with the EF objects from my instantiated context. My hacky work around is this: if (viewModel.ChildObjects.Count > 0) { foreach (ChildObject modelChildObject in viewModel.ChildObjects) { ChildObject childToUpdate = ParentObject.ChildObject.Where(a => a.ID == modelChildObject.ID).First(); childToUpdate.Name = modelChildObject.Name; } } This seems to work fine. My question to you good folks: Is there correct way to do this? I tried following the suggestion for making a custom model binder per the blog link I posted above but it didn't work (there was an issue with reflection) and I needed to get something going ASAP. PS - I tried to cleanup the code to hide specific information, so beware I may have hosed something up. I mainly just want to know if other people have solved this problem. Thanks!

    Read the article

  • Advice welcomed on creating my own Swing component

    - by Toto
    Recently I asked which was the best Swing component to bind to a BigDecimal variable (with some particular editing properties). It turns out that none of the standard Swing components suit me completely, nor did the third-party Swing component libraries I've found out there. So I’ve decided to create my own Swing component. Component description: I want to extend JTextField or JFormattedTextField, so my new component can be easily bound to a BigDecimal variable. The component will have customizable scale and length properties. Behavior: When the component is drawn, it shows only the decimal point and space for scale digits to its right. When the component receives focus the caret should be positioned left to the decimal point. As the user types numbers (any other character is ignored) they appear to the left of the caret, only length – scale numbers are accepted, any other number typed is ignored as the integer portion is full. Any time the user types the decimal point the caret moves to the right side of the decimal point. The following numbers typed are shown in the decimal part, only scale numbers are considered any other number typed is ignored as the decimal portion is full. Additionally, thousand separators should appear as the user types numbers left to the decimal point. Invoking a getValue() method on the component should yield the BigDecimal representing the number just entered. I’ve never created my own Swing component; I’ve barely used the standard ones. So I would appreciate any good tutorial/info/tip on creating the component described. This is the only thing I've got so far. Thanks in advance.

    Read the article

  • Dynamic Data - Make Friendly Column Names?

    - by davemackey
    I've created a Dynamic Data project with an Entity Framework model. It works nicely. But, right now it shows all my database tables with the db column names - which aren't always the most friendly (e.g. address_line_1). How can I got about giving these more friendly column titles that will display to the end user?

    Read the article

  • MVC 2 Entity Framework View Model Insert

    - by cannibalcorpse
    This is driving me crazy. Hopefully my question makes sense... I'm using MVC 2 and Entity Framework 1 and am trying to insert a new record with two navigation properties. I have a SQL table, Categories, that has a lookup table CategoryTypes and another self-referencing lookup CategoryParent. EF makes two nav properties on my Category model, one called Parent and another called CategoryType, both instances of their respective models. On my view that creates the new Category, I have two dropdowns, one for the CategoryType and another for the ParentCategory. When I try and insert the new Category WITHOUT the ParentCategory, which allows nulls, everything is fine. As soon as I add the ParentCategory, the insert fails, and oddly (or so I think) complains about the CategoryType in the form of this error: 0 related 'CategoryTypes' were found. 1 'CategoryTypes' is expected. When I step through, I can verifiy that both ID properties coming in on the action method parameter are correct. I can also verify that when I go to the db to get the CategoryType and ParentCategory with the ID's, the records are being pulled fine. Yet it fails on SaveChanges(). All that I can see is that my CategoryParent dropdownlistfor in my view, is somehow causing the insert to bomb. Please see my comments in my httpPost Create action method. My view model looks like this: public class EditModel { public Category MainCategory { get; set; } public IEnumerable<CategoryType> CategoryTypesList { get; set; } public IEnumerable<Category> ParentCategoriesList { get; set; } } My Create action methods look like this: // GET: /Categories/Create public ActionResult Create() { return View(new EditModel() { CategoryTypesList = _db.CategoryTypeSet.ToList(), ParentCategoriesList = _db.CategorySet.ToList() }); } // POST: /Categories/Create [HttpPost] public ActionResult Create(Category mainCategory) { if (!ModelState.IsValid) return View(new EditModel() { MainCategory = mainCategory, CategoryTypesList = _db.CategoryTypeSet.ToList(), ParentCategoriesList = _db.CategorySet.ToList() }); mainCategory.CategoryType = _db.CategoryTypeSet.First(ct => ct.Id == mainCategory.CategoryType.Id); // This db call DOES get the correct Category, but fails on _db.SaveChanges(). // Oddly the error is related to CategoryTypes and not Category. // Entities in 'DbEntities.CategorySet' participate in the 'FK_Categories_CategoryTypes' relationship. // 0 related 'CategoryTypes' were found. 1 'CategoryTypes' is expected. //mainCategory.Parent = _db.CategorySet.First(c => c.Id == mainCategory.Parent.Id); // If I just use the literal ID of the same Category, // AND comment out the CategoryParent dropdownlistfor in the view, all is fine. mainCategory.Parent = _db.CategorySet.First(c => c.Id == 2); _db.AddToCategorySet(mainCategory); _db.SaveChanges(); return RedirectToAction("Index"); } Here is my Create form on the view : <% using (Html.BeginForm()) {%> <%= Html.ValidationSummary(true) %> <fieldset> <legend>Fields</legend> <div> <%= Html.LabelFor(model => model.MainCategory.Parent.Id) %> <%= Html.DropDownListFor(model => model.MainCategory.Parent.Id, new SelectList(Model.ParentCategoriesList, "Id", "Name")) %> <%= Html.ValidationMessageFor(model => model.MainCategory.Parent.Id) %> </div> <div> <%= Html.LabelFor(model => model.MainCategory.CategoryType.Id) %> <%= Html.DropDownListFor(model => model.MainCategory.CategoryType.Id, new SelectList(Model.CategoryTypesList, "Id", "Name"))%> <%= Html.ValidationMessageFor(model => model.MainCategory.CategoryType.Id)%> </div> <div> <%= Html.LabelFor(model => model.MainCategory.Name) %> <%= Html.TextBoxFor(model => model.MainCategory.Name)%> <%= Html.ValidationMessageFor(model => model.MainCategory.Name)%> </div> <div> <%= Html.LabelFor(model => model.MainCategory.Description)%> <%= Html.TextAreaFor(model => model.MainCategory.Description)%> <%= Html.ValidationMessageFor(model => model.MainCategory.Description)%> </div> <div> <%= Html.LabelFor(model => model.MainCategory.SeoName)%> <%= Html.TextBoxFor(model => model.MainCategory.SeoName, new { @class = "large" })%> <%= Html.ValidationMessageFor(model => model.MainCategory.SeoName)%> </div> <div> <%= Html.LabelFor(model => model.MainCategory.HasHomepage)%> <%= Html.CheckBoxFor(model => model.MainCategory.HasHomepage)%> <%= Html.ValidationMessageFor(model => model.MainCategory.HasHomepage)%> </div> <p><input type="submit" value="Create" /></p> </fieldset> <% } %> Maybe I've just been staying up too late playing with MVC 2? :) Please let me know if I'm not being clear enough.

    Read the article

  • GUID or int entity key with SQL Compact/EF4?

    - by David Veeneman
    This is a follow-up to an earlier question I posted on EF4 entity keys with SQL Compact. SQL Compact doesn't allow server-generated identity keys, so I am left with creating my own keys as objects are added to the ObjectContext. My first choice would be an integer key, and the previous answer linked to a blog post that shows an extension method that uses the Max operator with a selector expression to find the next available key: public static TResult NextId<TSource, TResult>(this ObjectSet<TSource> table, Expression<Func<TSource, TResult>> selector) where TSource : class { TResult lastId = table.Any() ? table.Max(selector) : default(TResult); if (lastId is int) { lastId = (TResult)(object)(((int)(object)lastId) + 1); } return lastId; } Here's my take on the extension method: It will work fine if the ObjectContext that I am working with has an unfiltered entity set. In that case, the ObjectContext will contain all rows from the data table, and I will get an accurate result. But if the entity set is the result of a query filter, the method will return the last entity key in the filtered entity set, which will not necessarily be the last key in the data table. So I think the extension method won't really work. At this point, the obvious solution seems to be to simply use a GUID as the entity key. That way, I only need to call Guid.NewGuid() method to set the ID property before I add a new entity to my ObjectContext. Here is my question: Is there a simple way of getting the last primary key in the data store from EF4 (without having to create a second ObjectContext for that purpose)? Any other reason not to take the easy way out and simply use a GUID? Thanks for your help.

    Read the article

  • Azure Flavor for the Sharepoint Media Component

    - by spano
    Some time ago I wrote about a Media Processing Component for Sharepoint that I was working on. It is a Media Assets list for Sharepoint that lets you choose where to store the blob files. It provides also intelligence for encoding videos, generating thumbnail and poster images, obtaining media metadata, etc. On that first post the component was explained in detail, with the original 3 storage flavors: Sharepoint list, Virtual Directoy or FTP. The storage manager is extensible, so a new flavor was...(read more)

    Read the article

  • Ubuntu One Joomla 1.6 Component, for sharing content

    - by Chris Machens
    Hello, id like to support Ubuntu One, and enhance my project at http://biochar.me The website uses Joomla.org 1 of the most widely used CMS on the net and version 1.6 got released a few weeks ago. Now my question: Are there plans to deliver a component, to enhance the user experience for example with sharing files? http://joomlapolis.com releases their CB - Community Builder component for joomla on the 14th and for example a CB Plugin for Ubuntu One integration would be a great addition. Looking forward to your feedback.

    Read the article

  • Argument exception after trying to use TryGetObjectByKey

    - by Rickjaah
    Hi, I'm trying to retrieve an object from my database using entity (framework 4) When I use the following code it gives an ArgumentException: An item with the same key has already been added. if (databaseContext.TryGetObjectByKey(entityKey, out result)) { return (result != null && result is TEntityObject) ? result as TEntityObject : null; } else { return null; } When I check the objectContext, I see the entities, but only if I enumerate the specific list of entities manually using VS2010, it works. What am I missing? Do I have to do something else before i can get the item from the database? I have lazy loading set to true. I searched google, but could not find any results, the same for the msdn library

    Read the article

  • Need help understanding Generics, How To Abstract Types Question.

    - by kmacmahon
    I could use some really good links that explain Generics and how to use them. But I also have a very specific question, relater to working on a current project. Given this class constructor: public class SecuredDomainViewModel<TDomainContext, TEntity> : DomainViewModel<TDomainContext, TEntity> where TDomainContext : DomainContext, new() where TEntity : Entity, new() And its creation this way: DomainViewModel d; d = new SecuredDomainViewModel<MyContext, MyEntityType>(this.context, selectedProtectedItem); Assuming I have 20 EntityTypes within MyContext, is there any easier way to call the constructor without a large switch statement? Also, since d is DomainViewModel and I want to access methods for SecuredDomainViewModel, it seems I need to do this: if (((SecuredDomainViewModel<MyContext, MyEntityType>)d).IsBusy) But again "MyEntityType" could actually be one of 20 types. Is there anyway to write these types of statements where MyEntityType is returned from some sort of Reflection?

    Read the article

  • Need help understanding Generics, How To Abstract Types Question.

    - by kmacmahon
    I could use some really good links that explain Generics and how to use them. But I also have a very specific question, relater to working on a current project. Given this class constructor: public class SecuredDomainViewModel<TDomainContext, TEntity> : DomainViewModel<TDomainContext, TEntity> where TDomainContext : DomainContext, new() where TEntity : Entity, new() public SecuredDomainViewModel(TDomainContext domainContext, ProtectedItem protectedItem) : base(domainContext) { this.protectedItem = protectedItem; } And its creation this way: DomainViewModel d; d = new SecuredDomainViewModel<MyContext, MyEntityType>(this.context, selectedProtectedItem); Assuming I have 20 different EntityTypes within MyContext, is there any easier way to call the constructor without a large switch statement? Also, since d is DomainViewModel and I later need to access methods from SecuredDomainViewModel, it seems I need to do this: if (((SecuredDomainViewModel<MyContext, MyEntityType>)d).CanEditEntity) But again "MyEntityType" could actually be one of 20 diffent types. Is there anyway to write these types of statements where MyEntityType is returned from some sort of Reflection?

    Read the article

  • Instantiating a context in LINQ to Entities

    - by Jagd
    I've seen two different manners that programmers approach when creating an entity context in their code. The first is like such, and you can find it all over the MSDN code examples: public void DoSomething() { using TaxableEducationEntities context = new TaxableEducationEntities()) { // business logic and whatever else } } The second is to create the context as a private attribute in some class that encapsulates your business logic. So you would have something like: public class Education_LINQ { private TaxableEducationEntities context = new TaxableEducationEntities(); public void DoSomething() { var result = from a in context.luAction select a; // business logic and whatever else } } Which way is more efficient? Assume that you have two methods, one called DoSomething1() and another called DoSomething2(), and both methods incorporate the using statement to open the context and do whatever with it. Were you to call one method after the other, would there be any superfluous overhead going on, since essentially both methods create the context and then clean it up when they're done? As opposed to having just one private attribute that is created when a class object is instantiated, and then in turn cleaned up when the object goes out of scope?

    Read the article

  • How do I Relate these 4 Tables

    - by Baddie
    Trying to setup a simple Thread/Poll table mapping. Here is what I have: Threads table ThreadID (Primary Key/Identity Column) Polls table PollID (Primary Key, FK for ThreadID for one-to-one relation) Question PollOptions table PollOptionID (Identity/Primary Key) Text PollID PollVotes table PollVoteID (Primary Key/Identity) PollOptionID I'm not sure if this is a proper relationship. It seems wrong but I'm not sure whats wrong with it. A Thread can have 0 or 1 Poll. A Poll can have 2 or more PollOptions. A PollOption can have 0 or many PollVotes. I'm going to be using Entity Framework and before I generate the code for it (VS 2010, .NET 4) I want to make sure I have the proper relationship mapping.

    Read the article

< Previous Page | 27 28 29 30 31 32 33 34 35 36 37 38  | Next Page >