Using ASP.NET MVC5 I'm getting this error:
System.InvalidOperationException: Sequence contains more than one element
at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source)
at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__2[TResult](IEnumerable`1 sequence)
at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable`1 query, Expression queryRoot)
at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[TResult](Expression expression)
at System.Data.Entity.Internal.Linq.DbQueryProvider.Execute[TResult](Expression expression)
at System.Linq.Queryable.SingleOrDefault[TSource](IQueryable`1 source, Expression`1 predicate)
at System.Data.Entity.Migrations.DbSetMigrationsExtensions.AddOrUpdate[TEntity](DbSet`1 set, IEnumerable`1 identifyingProperties, InternalSet`1 internalSet, TEntity[] entities)
at System.Data.Entity.Migrations.DbSetMigrationsExtensions.AddOrUpdate[TEntity](IDbSet`1 set, Expression`1 identifierExpression, TEntity[] entities)
at ArtistDatabase.Migrations.Configuration.Seed(ArtistDBContext context) in C:\Users\Will\Desktop\ArtistDatabase\ArtistDatabase\Migrations\Configuration.cs:line 196
at System.Data.Entity.Migrations.DbMigrationsConfiguration`1.OnSeed(DbContext context)
at System.Data.Entity.Migrations.DbMigrator.SeedDatabase()
at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.SeedDatabase()
at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String targetMigration)
at System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClassc.<Update>b__b()
at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String targetMigration)
at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.Run()
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
at System.Data.Entity.Migrations.Design.ToolingFacade.Update(String targetMigration, Boolean force)
at System.Data.Entity.Migrations.UpdateDatabaseCommand.<>c__DisplayClass2.<.ctor>b__0()
at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
Sequence contains more than one element
These are my two modals, I'm new to this, but I'm not sure if it's because of them both having "Name" and "Picture", or because of the "ArtistID" in the Artwork modal, though it's supposed to be a foreign key.
Artists
public class Artist
{
public int ArtistID { get; set; }
//----------------------------------------------------------------------------------------------
[Required,StringLength(60, MinimumLength = 3), Display(Name = "Artist")]
public string Name { get; set; }
//----------------------------------------------------------------------------------------------
[DataType(DataType.ImageUrl)]
public string Picture { get; set; }
//----------------------------------------------------------------------------------------------
[System.ComponentModel.DataAnnotations.Schema.Column(TypeName = "datetime2")]
[Display(Name = "Date of Birth"),DataType(DataType.Date),DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime BirthDate { get; set; }
//----------------------------------------------------------------------------------------------
[Required,StringLength(30)]
public string Nationality { get; set; }
//----------------------------------------------------------------------------------------------
[Display(Name = "Style/Movement")]
public string ArtStyle { get; set; }
//----------------------------------------------------------------------------------------------
[DataType(DataType.MultilineText)]
public string Info { get; set; }
//----------------------------------------------------------------------------------------------
[RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$")]
[StringLength(5)]
public string Rating { get; set; }
//----------------------------------------------------------------------------------------------
[Display(Name = "Famous work: "),DataType(DataType.ImageUrl)]
public string Artwork1 { get; set; }
//----------------------------------------------------------------------------------------------
[Display(Name = " "), DataType(DataType.ImageUrl)]
public string Artwork2 { get; set; }
//----------------------------------------------------------------------------------------------
[Display(Name = " "), DataType(DataType.ImageUrl)]
public string Artwork3 { get; set; }
//----------------------------------------------------------------------------------------------
public virtual ICollection<Artwork> Artworks { get; set; }
}
public class ArtistDBContext : DbContext
{
public DbSet<Artist> Artists { get; set; }
public DbSet<Artwork> Artworks { get; set; }
}
Artwork
public class Artwork
{
public int ArtworkID { get; set; }
//------------------------------------------------------------------------
//foreign key for Artists
public int ArtistID { get; set; }
//------------------------------------------------------------------------
[StringLength(60), Display(Name = "Artist")]
public string Name { get; set; }
//------------------------------------------------------------------------
[Required, DataType(DataType.ImageUrl)]
public string Picture { get; set; }
//------------------------------------------------------------------------
[DataType(DataType.MultilineText)]
public string Info { get; set; }
//------------------------------------------------------------------------
public virtual Artist Artist { get; set;}
}
Migration Artwork(1)
public override void Up()
{
DropPrimaryKey("dbo.Artists");
DropColumn("dbo.Artists", "ID");
CreateTable(
"dbo.Artworks",
c => new
{
ArtworkID = c.Int(nullable: false, identity: true),
ArtistID = c.Int(nullable: false),
Name = c.String(),
Info = c.String(),
})
.PrimaryKey(t => t.ArtworkID)
.ForeignKey("dbo.Artists", t => t.ArtistID, cascadeDelete: true)
.Index(t => t.ArtistID);
AddColumn("dbo.Artists", "ArtistID", c => c.Int(nullable: false, identity: true));
AddPrimaryKey("dbo.Artists", "ArtistID");
}
public override void Down()
{
DropForeignKey("dbo.Artworks", "ArtistID", "dbo.Artists");
DropIndex("dbo.Artworks", new[] { "ArtistID" });
DropPrimaryKey("dbo.Artists");
DropColumn("dbo.Artists", "ArtistID");
DropTable("dbo.Artworks");
AddColumn("dbo.Artists", "ID", c => c.Int(nullable: false, identity: true));
AddPrimaryKey("dbo.Artists", "ID");
}
Migration ArtworkAnnotations(2)
public override void Up()
{
AlterColumn("dbo.Artworks", "Name", c => c.String(nullable: false, maxLength: 60));
}
public override void Down()
{
AlterColumn("dbo.Artworks", "Name", c => c.String());
}
Migration Picture(3)
public override void Up()
{
AddColumn("dbo.Artworks", "Picture", c => c.String());
}
public override void Down()
{
DropColumn("dbo.Artworks", "Picture");
}
Config.cs
nternal sealed class Configuration : DbMigrationsConfiguration<ArtistDatabase.Models.ArtistDBContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(ArtistDatabase.Models.ArtistDBContext context)
{
context.Artists.AddOrUpdate(i => i.Name,
new Artist
{
ArtistID = 1,
Name = "Pablo Ruiz y Picasso",
Picture = "http://a5.files.biography.com/image/upload/c_fit,cs_srgb,dpr_1.0,h_1200,q_80,w_1200/MTE1ODA0OTcxNzU0MDk2MTQx.jpg",
BirthDate = DateTime.Parse("25-10-1881"),
Nationality = "Spanish",
ArtStyle = "Cubism, Surrealism",
Info = "Picasso was a Spanish painter, sculptor and ceramicist, among other things. He spent most of his adult life in France, " +
" and is regarding as one of the greatest and most influential artists of the 20th century. He is known as co-founding of the" +
" 'Cubist' movement; the invention of constructed sculpture, also being the co-inventor of collage, and for the wide variety" +
" of styles that he helped develop and explore. Picasso, Henri Matisse and Marcel Duchamp are regarded as the three artists" +
" who most defined the revolutionary developments in the plastic arts in the opening decades of the 20th century, responsible" +
" for significant developments in painting, sculpture, printmaking and ceramics. Picasso demonstrated extraordinary artistic" +
" talent in his early years, painting in a naturalistic manner through his childhood and adolescence.During the first decade" +
" of the 20th century, his style changed as he experimented with different theories, techniques, and ideas.His work is often" +
" categorized into periods.While the names of many of his later periods are debated, the most commonly accepted periods in his" +
" work are the Blue Period(1901–1904), the Rose Period(1904–1906), the African - influenced Period(1907–1909)," +
" Analytic Cubism(1909–1912),and Synthetic Cubism(1912–1919),also referred to as the Crystal period. Exceptionally prolific" +
" throughout the course of his long life, Picasso achieved universal renown and immense fortune for his revolutionary artistic" +
" accomplishments, and became one of the best - known figures in 20th - century art.",
Artwork1 = "https://s-media-cache-ak0.pinimg.com/originals/34/c4/8c/34c48c9178f215e2670feec774036803.jpg",
Artwork2 = "http://paintingandframe.com/uploadpic/pablo_picasso/big/les_demoiselles_d_avignon_c_1907.jpg",
Artwork3 = "http://www.pablopicasso.org/images/paintings/blue-nude.jpg"
},
new Artist
{
ArtistID = 2,
Name = "Leonardo da Vinci",
Picture = "http://www.leonardodavinci.net/images/leonardo-da-vinci.jpg",
BirthDate = DateTime.Parse("15-04-1452"),
Nationality = "Italian",
ArtStyle = "High Renaissance",
Info = "Leonardo di ser Piero da Vinci was an Italian polymath whose areas of interest included invention, painting," +
" sculpting, architecture, science, music, mathematics, engineering, literature, anatomy, geology, astronomy, botany, writing, history," +
" and cartography. He has been variously called the father of palaeontology, ichnology, and architecture, and is widely considered one" +
" of the greatest painters of all time. Sometimes credited with the inventions of the parachute, helicopter and tank, he epitomised" +
" the Renaissance humanist ideal.Many historians and scholars regard Leonardo as the prime exemplar of the 'Universal Genius' or " +
"'Renaissance Man', an individual of 'unquenchable curiosity' and 'feverishly inventive imagination'. According to art historian Helen" +
" Gardner, the scope and depth of his interests were without precedent in recorded history, and 'his mind and personality seem to us" +
" superhuman, while the man himself mysterious and remote'. Marco Rosci notes that while there is much speculation regarding his life" +
" and personality, his view of the world was logical rather than mysterious, and that the empirical methods he employed were unorthodox" +
" for his time. Leonardo was, and is, renowned primarily as a painter. Among his works, the Mona Lisa is the most famous and most" +
" parodied portrait and The Last Supper the most reproduced religious painting of all time, their fame approached only by Michelangelo's" +
" The Creation of Adam. Leonardo's drawing of the Vitruvian Man is also regarded as a cultural icon, being reproduced on items as" +
" varied as the euro coin, textbooks, and T-shirts. Perhaps fifteen of his paintings have survived. Nevertheless, these few works," +
" together with his notebooks, which contain drawings, scientific diagrams, and his thoughts on the nature of painting, compose a" +
" contribution to later generations of artists rivalled only by that of his contemporary, Michelangelo.",
Artwork1 = "https://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Mona_Lisa,_by_Leonardo_da_Vinci,_from_C2RMF_retouched.jpg/402px-Mona_Lisa,_by_Leonardo_da_Vinci,_from_C2RMF_retouched.jpg",
Artwork2 = "https://upload.wikimedia.org/wikipedia/commons/2/23/Leonardo_da_Vinci_-_Last_Supper_(copy)_-_WGA12732.jpg",
Artwork3 = "http://blog.world-mysteries.com/wp-content/uploads/2011/01/vitruvian_man_mixed.jpg"
},
new Artist
{
ArtistID = 3,
Name = "Georgia O'Keeffe",
Picture = "http://1874.img.pp.sohu.com.cn/images/blog/2008/11/16/20/26/11e4d90ce26g213.jpg",
BirthDate = DateTime.Parse("15-11-1887"),
Nationality = "American",
ArtStyle = "American Modernism",
Info = "Georgia Totto O'Keeffe was an American artist. She is best known for her paintings of enlarged flowers, New York skyscrapers," +
" and New Mexico landscapes. O'Keeffe has been recognized as the 'Mother of American modernism'. O'Keeffe studied at the School of the" +
" Art Institute of Chicago from 1905 to 1906. In 1907, she attended the Art Students League in New York City, where she studied under" +
" William Merritt Chase. In 1908, she won the League's William Merritt Chase still-life prize for her oil painting Dead Rabbit with" +
" Copper Pot. Her prize was a scholarship to attend the League's outdoor summer school in Lake George, New York. While in the city" +
" in 1908, O'Keeffe attended an exhibition of Rodin's watercolors at the gallery 291, owned by her future husband, photographer Alfred" +
" Stieglitz. O'Keeffe abandoned the idea of pursuing a career as an artist in late 1908, claiming that she could never distinguish" +
" herself as an artist within the mimetic tradition which had formed the basis of her art training. She took a job in Chicago as" +
" a commercial artist. She did not paint for four years, and said that the smell of turpentine made her sick. She was inspired to" +
" paint again in 1912, when she attended a class at the University of Virginia Summer School, where she was introduced to the innovative" +
" ideas of Arthur Wesley Dow by Alon Bement. Dow encouraged artists to express themselves using line, color, and shading" +
" harmoniously. From 1912-14, she taught art in the public schools in Amarillo in the Texas Panhandle. She attended Teachers College" +
" of Columbia University from 1914–15, where she took classes from Dow, who greatly influenced O'Keeffe's thinking about the process of" +
" making art. She served as a teaching assistant to Bement during the summers from 1913–16 and taught at Columbia College, Columbia," +
" South Carolina in late 1915, where she completed a series of highly innovative charcoal abstractions. After further course work at" +
" Columbia in early 1916 and summer teaching for Bement, she took a job as head of the art department at West Texas State Normal College" +
" from late 1916 to February 1918, the fledgling West Texas A&M University in Canyon just south of Amarillo. While there, she often" +
" visited the Palo Duro Canyon, making its forms a subject in her work.",
Artwork1 = "http://www.georgiaokeeffe.net/images/paintings/rams-head.jpg",
Artwork2 = "https://learnodo-newtonic.com/wp-content/uploads/2015/09/Red-Canna-1924-Georgia-OKeeffe.jpg",
Artwork3 = "http://www.themasterpiececards.com/hs-fs/hub/40667/file-25876050-jpg/images/okeeffe_jack_2_from_nga-resized-600.jpg?t=1465250810631"
},
new Artist
{
ArtistID = 4,
Name = "Vincent van Gogh",
Picture = "http://site.artsheaven.com/blog/wp-content/uploads/2015/10/vincent.jpg",
BirthDate = DateTime.Parse("30-03-1853"),
Nationality = "Dutch",
ArtStyle = "Post-Impressionism",
Info = "Vincent Willem van Gogh was a Dutch painter who is among the most famous and influential figures in the history of Western art." +
" In just over a decade he created about 2100 artworks, including around 860 oil paintings, most of them in the last two years of his" +
" life. They include landscapes, still lifes, portraits and self-portraits, and are characterised by bold, symbolic colours, and" +
" dramatic, impulsive and highly expressive brushwork that contributed to the foundations of modern art. He sold only one painting" +
" during his lifetime and became famous after his suicide at age 37, which followed years of poverty and mental illness. Van Gogh's" +
" early works, mostly still lifes and depictions of peasant labourers, contain few signs of the vivid colour that distinguished his" +
" later work. In 1886 he moved to Paris and discovered the French Impressionists. As his work developed he created a new approach to" +
" still lifes and local landscapes. His paintings grew brighter in colour as he developed a style that became fully realised during his" +
" stay in Arles in the south of France in 1888. He lived there in the Yellow House and, with the French artist Paul Gauguin, developed a" +
" concept of colour that symbolised inner emotion. During this period he broadened his subject matter to include olive trees, cypresses," +
" wheat fields and sunflowers. In Nuenen, Van Gogh focused on painting and drawing. Working outside and very quickly, he completed" +
" sketches and paintings of weavers and their cottages. In August 1884, Margot Begemann, a neighbour's daughter and ten years" +
" his senior, began joining him on his painting forays; she fell in love, and he reciprocated, though less enthusiastically. They" +
" decided to marry, but the idea was opposed by both families, following which Margot took an overdose of strychnine. She was saved" +
" when Van Gogh rushed her to a nearby hospital. On 26 March 1885, his father died of a heart attack. Van Gogh painted several" +
" groups of still lifes in 1885. During his two - year stay in Nuenen, he completed numerous drawings and watercolours, and nearly" +
" 200 oil paintings.His palette consisted mainly of sombre earth tones, particularly dark brown, and showed no sign of the vivid colours" +
" that distinguish his later work.Considered a madman and a failure in his lifetime,Van Gogh exists in the public imagination as the" +
" quintessential misunderstood genius, the artist 'where discourses on madness and creativity converge'.His reputation began to grow" +
" in the early 20th century as elements of his painting style came to be incorporated by the Fauves and German Expressionists.He attained" +
" widespread critical, commercial and popular success over the ensuing decades, and is remembered as an important but tragic painter," +
" whose troubled personality typifies the romantic ideal of the tortured artist.",
Artwork1 = "https://upload.wikimedia.org/wikipedia/commons/9/94/Starry_Night_Over_the_Rhone.jpg",
Artwork2 = "https://upload.wikimedia.org/wikipedia/commons/thumb/7/76/Vincent_van_Gogh_-_De_slaapkamer_-_Google_Art_Project.jpg/1280px-Vincent_van_Gogh_-_De_slaapkamer_-_Google_Art_Project.jpg",
Artwork3 = "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b4/Vincent_Willem_van_Gogh_128.jpg/175px-Vincent_Willem_van_Gogh_128.jpg"
},
new Artist {
ArtistID = 5,
Name = "Salvador Dali",
Picture = "https://s-media-cache-ak0.pinimg.com/originals/4b/78/e7/4b78e72934aa5cdcb6a8bff7b23b4b51.jpg",
BirthDate = DateTime.Parse("11-05-1904"),
Nationality = "Spanish",
ArtStyle = "Cubism, Dada, Surrealism",
Info = "",
Artwork1 = "https://upload.wikimedia.org/wikipedia/en/4/43/Dali_Elephants.jpg",
Artwork2 = "http://www.dalipaintings.net/images/paintings/dream-caused-by-the-flight-of-a-bee.jpg",
Artwork3 = "http://www.dalipaintings.net/images/paintings/swans-reflecting-elephants.jpg",
},
new Artist
{
ArtistID = 6,
Name = "Andy Warhol",
Picture = "https://upload.wikimedia.org/wikipedia/commons/2/2b/Andy_Warhol_by_Jack_Mitchell.jpg",
BirthDate = DateTime.Parse("06-08-1928"),
Nationality = "American",
ArtStyle = "Pop art",
Info = "",
Artwork1 = "https://upload.wikimedia.org/wikipedia/en/thumb/1/1f/Campbells_Soup_Cans_MOMA.jpg/300px-Campbells_Soup_Cans_MOMA.jpg",
Artwork2 = "https://vmfa.museum/collections/wp-content/uploads/sites/9/2013/12/Warhol_85_453_v1_KW_200909_XL-878x1024.jpg",
Artwork3 = "https://cdn.kastatic.org/ka-perseus-images/329f84364bd08b80515b71fa830da2d2b6802c0c.jpg",
},
new Artist
{
ArtistID = 7,
Name = "Michelangelo",
Picture = "https://upload.wikimedia.org/wikipedia/commons/5/5e/Miguel_%C3%81ngel,_por_Daniele_da_Volterra_(detalle).jpg",
BirthDate = DateTime.Parse("06-03-1475"),
Nationality = "Italian",
ArtStyle = "High Renaissance",
Info = "",
Artwork1 = "https://upload.wikimedia.org/wikipedia/commons/b/b4/Michelangelo_-_Creation_of_Adam.jpg",
Artwork2 = "https://upload.wikimedia.org/wikipedia/commons/2/24/'David'_by_Michelangelo_JBU0001.JPG",
Artwork3 = "http://www.italianrenaissance.org/wp-content/uploads/2012/07/Michelangelo-pieta.jpg",
},
new Artist
{
ArtistID = 8,
Name = "Claude Monet",
Picture = "http://www.notesontheroad.com/images/stories/yings_links/Birthdays/Monet/claude-monet.jpg",
BirthDate = DateTime.Parse("14-11-1840"),
Nationality = "French",
ArtStyle = "Impressionism",
Info = "",
Artwork1 = "",
Artwork2 = "",
Artwork3 = "",
}
);
context.Artworks.AddOrUpdate(i => i.ArtistID,
new Artwork
{
ArtworkID = 1,
ArtistID = 1,
Name = "Guernica",
Picture = "https://upload.wikimedia.org/wikipedia/en/7/74/PicassoGuernica.jpg",
Info = "",
},
new Artwork
{
ArtworkID = 2,
ArtistID = 1,
Name = "The Weeping Woman",
Picture = "http://totallyhistory.com/wp-content/uploads/2012/12/pablo-picasso-weeping-woman.jpg",
Info = "",
},
new Artwork
{
ArtworkID = 3,
ArtistID = 1,
Name = "Three Musicians",
Picture = "http://www.pablopicasso.org/images/paintings/three-musicians.jpg",
Info = "",
},
new Artwork
{
ArtworkID = 4,
ArtistID = 1,
Name = "Le Rêve",
Picture = "https://upload.wikimedia.org/wikipedia/en/9/9d/Le-reve-1932.jpg",
Info = "",
}
);
When you seed your Artworks
, you are not using AddOrUpdate
correctly.
It expects a unique identifier, so instead of:
context.Artworks.AddOrUpdate(i => i.ArtistID,
You should use:
context.Artworks.AddOrUpdate(i => i.ArtworkID,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With