Sequence contains more than one element error in MVC 5

I created some models, added the migration and then did an update database operation, though at my last update database operation I got the error message saying:
    Sequence contains more than one element
Below you can find my migration configuration:
        context.Categories.AddOrUpdate(p => p.CategoryName,
            new Category
                CategoryName = "Sport"
            new Category
                CategoryName = "Music"
        context.Subcategories.AddOrUpdate(p => p.SubcategoryName,
            new Subcategory
                SubcategoryName = "Football"
            new Subcategory
                SubcategoryName = "Basketball"
            new Subcategory
                SubcategoryName = "Piano"
            new Subcategory
                SubcategoryName = "Violin"
        context.Services.AddOrUpdate(p => p.ServiceType,
            new Service
                ServiceType = "Football player",
                Category = { CategoryName = "Sport" },
                Subcategory = { SubcategoryName = "Football" }
            new Service 
                ServiceType = "Piano lessons",
                Category = { CategoryName = "Music" },
                Subcategory = { SubcategoryName = "Piano" }
The problem occurs with when I add new Services. I already have categories and subcategories, and if I do like Category = new Category { CategoryName = "Music" } then it works but I get Music entry twice in my database (for this example). I want to
use the already added categories and subcategories. Below also you can find my models definitions.
public class Category
    [Key]
    public int CategoryID { get; set; }
    public string CategoryName { get; set; }
// Subcategory is defined the same way...
public class Service
    public int ServiceID { get; set; }
    public string ServiceType { get; set; }
    public virtual Category Category { get; set; }
    public virtual Subcategory Subcategory { get; set; }
}

After reading the article in the link that you have provided, I did the following changes in my models, and created controllers for each of them using Entity Framework, then I created a migration and named it InitialServices. Afterwards, I added a few
entries in my Configuration.cs file and when I typed Update-Database, I got an error message in package manager saying "RenameIndexOperation", which is marked with red. Below you can find my changed models and my Configuration.cs file, along with the migration
file created automatically.
Category.cs:
    public class Category
        [Key]
        public int CategoryID { get; set; }
        public string CategoryName { get; set; }
        public virtual ICollection<Subcategory> Subcategories { get; set; }
Subcategory.cs:
    public class Subcategory
        [Key]
        public int SubcategoryID { get; set; }
        public string SubcategoryName { get; set; }
        [ForeignKey("Category")]
        public int CategoryID { get; set; }
        public virtual Category Category { get; set; }
        public virtual ICollection<Service> Services { get; set; }
Service.cs:
    public class Service
        [Key]
        public int ServiceID { get; set; }
        [Required]
        [Display(Name="Service type")]
        public string ServiceType { get; set; }
        [ForeignKey("Subcategory")]
        public int SubcategoryID { get; set; }
        public int Count { get; set; }
        public virtual Subcategory Subcategory { get; set; }
_InitialServices.cs:
    public partial class InitialServices : DbMigration
        public override void Up()
            DropForeignKey("dbo.Services", "Category_CategoryID", "dbo.Categories");
            DropIndex("dbo.Services", new[] { "Category_CategoryID" });
            RenameColumn(table: "dbo.Services", name: "Subcategory_SubcategoryID", newName: "SubcategoryID");
            RenameIndex(table: "dbo.Services", name: "IX_Subcategory_SubcategoryID", newName: "IX_SubcategoryID");
            AddColumn("dbo.Subcategories", "CategoryID", c => c.Int(nullable: false));
            CreateIndex("dbo.Subcategories", "CategoryID");
            AddForeignKey("dbo.Subcategories", "CategoryID", "dbo.Categories", "CategoryID", cascadeDelete: true);
            DropColumn("dbo.Services", "Category_CategoryID");
        public override void Down()
            AddColumn("dbo.Services", "Category_CategoryID", c => c.Int(nullable: false));
            DropForeignKey("dbo.Subcategories", "CategoryID", "dbo.Categories");
            DropIndex("dbo.Subcategories", new[] { "CategoryID" });
            DropColumn("dbo.Subcategories", "CategoryID");
            RenameIndex(table: "dbo.Services", name: "IX_SubcategoryID", newName: "IX_Subcategory_SubcategoryID");
            RenameColumn(table: "dbo.Services", name: "SubcategoryID", newName: "Subcategory_SubcategoryID");
            CreateIndex("dbo.Services", "Category_CategoryID");
            AddForeignKey("dbo.Services", "Category_CategoryID", "dbo.Categories", "CategoryID", cascadeDelete: true);
Configuration.cs:
protected override void Seed(Workfly.Models.ApplicationDbContext context)
            var categories = new List<Category>
                new Category { CategoryName = "Sport" },
                new Category { CategoryName = "Music" }
            categories.ForEach(c => context.Categories.AddOrUpdate(p => p.CategoryName, c));
            context.SaveChanges();
            var subcategories = new List<Subcategory>
                new Subcategory { SubcategoryName = "Football", CategoryID = categories.Single(c => c.CategoryName == "Sport").CategoryID },
                new Subcategory { SubcategoryName = "Basketball", CategoryID = categories.Single(c => c.CategoryName == "Sport").CategoryID },
                new Subcategory { SubcategoryName = "Piano", CategoryID = categories.Single(c => c.CategoryName == "Music").CategoryID },
                new Subcategory { SubcategoryName = "Violin", CategoryID = categories.Single(c => c.CategoryName == "Music").CategoryID }
            foreach (Subcategory s in subcategories)
                var subcategoriesInDB = context.Subcategories.Where(c => c.Category.CategoryID == s.CategoryID).SingleOrDefault();
                if (subcategoriesInDB == null)
                    context.Subcategories.Add(s);
            context.SaveChanges();
            var services = new List<Service>
                new Service { ServiceType = "Football coach", SubcategoryID = subcategories.Single(s => s.SubcategoryName == "Football").SubcategoryID },
                new Service { ServiceType = "Piano lessons", SubcategoryID = subcategories.Single(s => s.SubcategoryName == "Music").SubcategoryID }
            foreach (Service s in services)
                var servicesInDB = context.Services.Where(t => t.Subcategory.SubcategoryID == s.SubcategoryID).SingleOrDefault();
                if (servicesInDB == null)
                    context.Services.Add(s);
            context.SaveChanges();
        }

Similar Messages

  • Sequence contains more than one matching element

    Hi
    I have checked all threads and none answers my issue.
    I am trying to drop a user and am following this blog:
    http://sanderstechnology.com/2013/login-and-user-management-in-sql-azure/12826/#.U46Hh_mSweo
    Below is a series of screen-shots of the issue. Please assist. Thanks, Mark.
    Mark

    Hello,
    Based on your descritpion, you create a SQL database with WEB edition and try to connect to the MASTER database from Windows Azure Management portal. But it is failed with "Sequence contains more than one matching element" occasionally.
    Due to the uncertainty and randomness factors, it requires higher level troubleshooting methods.I suggest you contact Windows Azure support team by creating a support ticket at 
    http://www.windowsazure.com/en-us/support/contact if you recevied this error again.
    As for drop login, it may caused by the premssion. In SQL databae, only server-level principal login (created by the provisioning process) or the credentials of an existing member of the "loginmanager" database role can manage logins. If you are not use
    a server-level principal login, please ask the adminstrator add the login to loginmanager databaserole:
    EXEC sp_addrolemember 'loginmanager', 'login-you-used';
    Reference:http://msdn.microsoft.com/en-us/library/azure/ee336235.aspx
    Regards,
    Fanny Liu
    If you have any feedback on our support, please click here. 
    Fanny Liu
    TechNet Community Support

  • The "Measures" dimension contains more than one hierarchy... Collation issue

    It appears that an Excel query pased through to SSAS has a "measures" with lowercase "m" when analysis services expects an uppercase "M" so it should look like "Measures". Is there a fix in excel to allow
    the correct passing of "Measures" member name to the cube?
    BTW, I have NO Calculations in the cube.
    In excel 2013 when I pivot with a pivot table connected to a case sensitive collation (non default config)
    cube and perform a filter by "Keep only Selected Items" I get the error "The 'Measures' dimension contains more than one hierarchy, therefore the hierarchy must be explicity specified".
    When I revert back to server wide setting to case insensitive, and I preform the exact same pivoting function it works without error. The problem appears to be that excel does not understand the server collation setting.
    When I run SQL Server Profilier I narrowed down the MDX statement run in Excel that gives me an error to this:
    with
    member measures.__XlItemPath as
    Generate(
    Ascendants([Employee].[Location Code].currentmember),
    [Employee].[Location Code].currentmember.unique_name,
    "|__XLPATHSEP__|"
    member measures.__XlSiblingCount as
    Generate(
    Ascendants([Employee].[Location Code].currentmember),
    AddCalculatedMembers([Employee].[Location Code].currentmember.siblings).count,
    "|__XLPATHSEP__|"
    member measures.__XlChildCount as
    AddCalculatedMembers([Employee].[Location Code].currentmember.children).count
    select { measures.__XlItemPath, measures.__XlSiblingCount, measures.__XlChildCount } on columns,
    [Employee].[Location Code].&[01W]
    dimension properties MEMBER_TYPE
    on rows
    from [Metrics]
    cell properties value
    Playing around with the query I discovered that if I capitalize the first letter of the "with measures" member, the statement works.
    with
    member Measures.__XlItemPath as
    Generate(
    Ascendants([Employee].[Location Code].currentmember),
    [Employee].[Location Code].currentmember.unique_name,
    "|__XLPATHSEP__|"
    member Measures.__XlSiblingCount as
    Generate(
    Ascendants([Employee].[Location Code].currentmember),
    AddCalculatedMembers([Employee].[Location Code].currentmember.siblings).count,
    "|__XLPATHSEP__|"
    member Measures.__XlChildCount as
    AddCalculatedMembers([Employee].[Location Code].currentmember.children).count
    select { measures.__XlItemPath, measures.__XlSiblingCount, measures.__XlChildCount } on columns,
    [Employee].[Location Code].&[01W]
    dimension properties MEMBER_TYPE
    on rows
    from [Metrics]
    cell properties value
    Also, I realise that I could change the collation on just the cube itself to case insenstive to get this to work, but I really don't want to do an impact analysis of running a mixed collation environment.
    So, my question is: Is there an excel fix that will allow me to run a case sensitve cube and allow me to click on filter and filter by "keep only selected items" or "Hide selected Items"? All other filtering works, it's only those two
    filtering options error for me.
    Here are the versions I'm working with:
    Excel 2013 (15.0.4535.1507) MSO(15.0.4551.1007) 32-bit Part of Microsoft Office Professional Plus 2013
    Microsoft Analysis Server Enterprise 2012 11.0.3000.0
    Any help would be appreciated. Thank you in advance!

    Hi, i assume this logic is for Dimension formula?
    If you have multiple hierarchy like ParentH1 and ParentH2 you should use FormulaH1 and FormulaH2 and not FORMULA column.
    in FORMULAH1
    [Account.H1].[Account_A] / [Account.H1].[Account_B]

  • Source system contain more than one fold then they are not processed

    when a mail box for a source system contain more than one fold they are not necessarily manage in the right sequence order (FIFO)
    The folders stand for material update flows.

    Hi   XI   Experts,
    I have a problem with source directory of the File Adapter,
    XI system is not reading the files from the source directory in the sequence when there is more than one folder .
    See the below description regarding the same.
    "when a mail box for a source system contain more than one fold they are not necessarily manage in the right sequence order (FIFO)
    The folders stand for material update flows."
    Please update me as soon as possible.
    Regards
    sreenivasulu

  • Align more than one element in same line in a selection screen

    I have to align more than one element
    in same line in a selection screen.
    It is possible with the following code.
    now the problem is i need space between these elements. how can i achieve it?
    SELECTION-SCREEN BEGIN OF LINE.
      SELECTION-SCREEN COMMENT (8) txt1.
      PARAMETERS :      location AS CHECKBOX,
                  loc(5) TYPE c.
      SELECTION-SCREEN COMMENT (15) txt2.
      PARAMETERS :     dept AS CHECKBOX,
                  dpt(5) TYPE c.
      SELECTION-SCREEN COMMENT (7) txt3.
      PARAMETERS :  product AS CHECKBOX,
                   prdt(5) TYPE c.
      SELECTION-SCREEN END OF LINE.

    Hi,
    Use SELECTION-SCREEN POSITION option.
    ex: SELECTION-SCREEN POSITION 15.
    Sample code:
    selection-screen: begin of block blk1 with frame.
    selection-screen: begin of line.
    parameters: R1 RADIOBUTTON GROUP RAD1.
    SELECTION-SCREEN position 5.
    SELECTION-SCREEN COMMENT 6(5) comm1.
    parameters: R2 RADIOBUTTON GROUP RAD1.
    SELECTION-SCREEN position 14.
    SELECTION-SCREEN COMMENT 15(5) comm2.
    selection-screen: end of line.
    selection-screen: end of block blk1.
    initialization.
    comm1 = 'File1'.
    comm2 = 'File2'.
    Edited by: Velangini Showry Maria Kumar Bandanadham on May 27, 2008 2:54 PM

  • How to create an iBOT which contains more than one dashboard page

    Hi,
    I want to create an iBOT which delivers the content in HTML or PDF format, but to contain more than one dashboard page. The idea is that I have several dashboards and I want to send by e-mail (by iBOT) most important pages from different dashboards.
    Is it possible to send by a single e-mail different pages from different dashboards? I cannot find an way to accomplish this in the content of delivery in iBOT.
    Thank you.

    Hi,
    Yes, I can add them to a briefing book, but the clients that will receive it by e-mail should have the briefing book reader in order to view the contents. Is there any way to send the briefing book in a PDF format?
    Thank you.

  • New iTunes on Mac doesn't allow me anymore to select all songs and 'Get info' to adjust the volume, like the old one. It says"your selection contains more than one type of media". They are all songs! Help please!

    New iTunes on Mac doesn't allow me anymore to select all songs and 'Get info' to adjust the volume, like the old one. It says"your selection contains more than one type of media". They are all songs! Help please!

    Raya Alfa wrote:
    ...there are some that are mp3 and it will be extremely hard to pick them from the lot.
    Not true. Select "Kind" as a sort category by right clicking the headings
    Then click to sort by Kind
    If your Import Settings are for Apple Lossless, AIFF, AAC or whatever the majority of your files are, convert MP3s to that file type.
    I've presently got 17,000+ files in my library, and they're ALL MP3 or M4B(Audiobooks). If they weren't when I got them, I converted them.  Saves a LOT of hassels with just this type of situation. Besides I have two non Apple MP3 players that WON'T work with other file types besides MP3 so, EVERYTHING I have has to be MP3.

  • Use of layout when more than one parameter - Error Missing Parameter Values

    Hi,
    Is it possible to use a crystal report which has more than one parameter as the layout for the bill of materials report.
    I have 3 parameters
           1. DocKey@       The Bill of Materials to be printed
           2. Number of levels to be printed
           3. type of levels to print.
    When I try to print it gives me the error Missing Parameter Values.
    I have tried changing the DocKey@ to CodeKey@ but the same error.
    Does anyone now where to find a list of these tokens?
    Thanks
    Chris

    I looked at the crystal report conversion to try to find what parameters it used and found none.
    I have managed to create and use a crystal report to replace the production order using DocKey@ as the parameter.  This works within SAP.  However I have converted the system production order to crystal reports and from the converted report I cannot see any parameters at all.
    How and where can you find out what paramters you need to use to replace any PLD report?  Several reports have multiple selection criteria before the report prints.  How can you find out what their tokens are called?  I am starting to pull my hair out.  I am getting great help from this forum, but do you know any documentation which actually explains this area.
    Thanks
    Chris

  • Conditions for regions depending on more than one element

    Good morning,
    I've got an easy question: I want a region only to be shown, when elements (:P1_x, :P1_y, :P1_z) are null. this is no problem if showing region depends on only one element:
    "Der Wert des Elements in Ausdruck1 ist NOT NULL" --&gt; so Ausdruck1 is filled with: P1_x
    But how can I simplfy APEX, that showing region depends on more then only this one element . I tried with AND (P1_x and P1_y and P1_z) or with semikolon (P1_x; P1_y; P1_z), but it doesn't work.
    So how can I tell APEX more than only one condition for showing region?
    thank you...

    Bettina,
    Condition type of:
    PL/SQL Expression
    Expresion:
    :P1_ITEM1 IS NULL
    AND
    :P1_ITEM2 IS NULL
    AND
    :P1_ITEM3 IS NULL
    Does that solve your problem?
    Andy

  • BUG?  ViewObject contains more than one Row with equal Key objects

    JDeveloper 10.1.2.1 build 1913
    JClient app
    aView
    ----bView
    --------cView
    ------------dView
    BEFORE:
    cView's detail row set contains two dViewRowImpl rows, as expected:
    row 0: key = 100
    row 1: key = 101
    ACTION:
    An attribute, X, in dView is modified by the user, which results in a call to setX in dViewRowImpl.
    In setX we have:
    1) setAttributeInternal for X
    2) transaction.postChanges
    3) a call to a procedure in the database to update dependent fields in the same row
    4) clearEntityCache on the primary entity of dView
    5) setAttributeInternal on a calculated attribute
    AFTER:
    cView's detail row set contains three dViewRowImpl rows, two of which have the same primary key:
    actual:
    row 0: key = 100
    row 1: key = 101
    row 2: key = 101
    expected (no change, and unique primary keys):
    row 0: key = 100
    row 1: key = 101
    Any clues appreciated.

    If your procedure modifies only the current row, or predetermined rows, you can
    // see Row.refresh
    transaction.postChanges();
    // refresh current row
    refresh(REFRESH_WITH_DB_FORGET_CHANGES);
    // or iterate over procedure-modified rows and refresh eachas an alternative to clearEntityCache. This alternative has the major benefit of not resetting currency in all ViewObjects touched by the cleared Entity. Luckily, this alternative has avoided the problem for us. If your code cannot predict which rows will be updated by your procedure, then you're still in trouble since JBO is apparently more than willing to insert duplicate Row objects into a ViewObject's RowSet after a clearEntityCache.

  • How could I get the pdf-file output to contain more than one page from certain homepages

    2011-08-22
    I have been using Firefox for many years now. I like this browser better than Safari. However. I have a problem when I have connected to a homepage over the web and want to write the content out to a pfd-file. The pdf-file does sometimes contain only one page. The material is good enough for two or more pages of output. I have checked that using Safari browser. I´d like to continue using Firefox so please tell med what to do!
    Göran Stille
    [email protected]
    Computer Mac Powerbook G4
    Processor 1.67 GHz PowerPC G4
    Operative system OSX 10.5.8
    Firefox version 3.6.2

    excellent.
    quiteimposing does exactly what i wanted.
    thanks a lot.
    now only problem is that demo version prints large x mark on pages
    is there any free plugins available or any other way to get rid of x mark.
    thanks in advance.

  • Is it okay to have more than one Elements on my computer?

    I have a DELL 660. It came with BOTH Adobe Photoshop Elements 9 AND Adobe Premiere Elements 9.
    I had always thought you should only have one type of a program installed at one time. I have not been able to use Elements correctly since getting the computer 2 years ago and I am finally forced to find out what to do. I have had to uninstall Elements again due to major problems.
    If I use both, does it matter which one I install first? How do I know which one to use at any given time?
    If I should use one, which one should I use?
    Please help!!

    Premiere Elements (video editor) and Photoshop Elements (photo editor) are totally different programs. It's like asking if it's okay to have Word or Reader and PSE on your computer together.
    However, it's also okay to have many versions of PSE on your computer. In older versions of windows you shouldn't try to run two versions of PSE at once, but there's no problem at all with having as many versions of the program as are compatible with your operating system.

  • How to generate a report with more than one elements in the same graph??

    I need to generate a custom report in OEM GC 10g featuring volume total capacity information and volume free capacity information both in the same graph on (Y-axis) and time on the (X-axis). I could generate only the total volume capacity graph individually, but how can the combined graph and the graph for free capacity be generated...

    Is it your values in parameter NO separated by coma? And is it
    parameter in where clause?
    Do you want something like :
    from table
    where s_no in (NO) ?
    If is answer "yes" you can create lexical parameter in report.
    You can write in report sowething like:
    select a.field1, a.field2,.....
    from table a
    &COND /* this is if is condition only one line after "from".
    if you have more lien after where then you will put this &COND
    in line where you want to have your multivalue.
    Then in your trigger in form you should write:
    sc_no := 'where a.sc_no in ('||:searchlist.c_no||')';
    ADD_PARAMETER(PL_ID, 'pamametername', TEXT_PARAMETER, sc_no);
    /* again this is if you have only one line with WHERE ili
    conditions */
    or you will write:
    sc_no := 'and a.sc_no in ('||:searchlist.c_no||')';
    ADD_PARAMETER(PL_ID, 'pamametername', TEXT_PARAMETER, sc_no);
    It will substitute line in which is your conditions with
    multivalue.

  • How to map when the Context node has more than one element

    Dear SDN Community,
      I am develping a WebDynpro java application with Adobe forms. My goal is to present a user a screen with 10 records of customer details and submit. I have created a context element for the customer(Cust#, address details etc) and mentioned the cardinality as 1..n. Now How do I bind these 10 records in my data view to first element, second element... 10th element of the context. Once the user submits, I need to write the 10 record values to Z table. Can you please advice me here.
    Thanks!
    Surya.

    solved this problem by going through the Interactive forms tutorial.

  • Validation of XML with Schema, which contains more than one Schema

    Hi All,
    I am having a parent.xsd file, which inculdes or imports child.xsd file. I need to validate an xml with the parent xsd. Could u give any sample code for doing the same.
    Java Version : 1.4.2
    Using Xerces for parsing the xml....
    Thanks,
    Senthil

    Is anyone there to reply?

Maybe you are looking for

  • App Store Difference Between Countries

    Hello there Do apps still differ between stores in different countries? I have changed addresses (moved to another country) and was wondering if moving to the new app store would limit access to some apps that are available only in either stores. Tha

  • Not all iTunes playlists are syncing on my iPhone

    These are not Smart Playlists, just plain vanilla manual playlists. iPhone 5 with latest iOS installed. Windows 7 with latest iTunes installed. I've removed the Music Library entirely from the iPhone, then re-synced with the "Entire Music Library" ra

  • Form Builder 6.0.8 (Solaris) Keyboard Shortcut Keys

    I am having no luck getting the keyboard shortcut keys to work inside Form Builder (e.g. Ctrl+j for connect) or during run time (e.g. Alt+11 for Execute Query).

  • Problem with a stored procedure (Error(4,1): PLS-00428: an INTO clause..)

    Dear Oracle Experts, I try to use the stored procedure below but get this error : "Error(4,1): PLS-00428: an INTO clause is expected in this SELECT statement" I don't have any clue what could be wrong with my syntax. INTO wouldn't make any sense at t

  • Content-Length missing in SOAP request

    In Oracle Application Server, a SOAP request like : POST /eai_esn/start.swe?SWEExtSource=WebService&SWEExtCmd=Execute&WSSoap=1 HTTP/1.1 SOAPAction: "document/http://siebel.com/marketing/import:MktgImportServiceInvokeImportJob" User-Agent: Axis2 Host: