Entity Framework Migrations Error : Sequence contains no elements - Timestamp - c#

I have been create a project in VS2015 with entity framework 6 - Code First with
EntityFramework [6.0.0.0]
mysql.data.entity.EF6 [6.8.3.0]
I am try Migrations
command: Add-Migration Initial
error: Sequence contains no matching element
I've been trying a bunch of things, and get the cause of this
[Timestamp]
public byte[] RowVersion { get; set; }
this is the sample model-code first
using MySql.Data.Entity;
using System.Data.Common;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace TokoBersama.Model
{
// Code-Based Configuration and Dependency resolution
[DbConfigurationType(typeof(MySqlEFConfiguration))]
public class MySqlDatabaseConnection : DbContext
{
#region Tabels
public DbSet<returnpenjualan> ReturnPenjualan { get; set; }
#endregion
#region member Event
public MySqlDatabaseConnection()
: base("name=myConnectionString")
{
}
public MySqlDatabaseConnection(DbConnection existingConnection, bool contextOwnsConnection)
: base(existingConnection, contextOwnsConnection)
{
}
//protected override void OnModelCreating(DbModelBuilder modelBuilder)
//{
// base.OnModelCreating(modelBuilder);
//
// Map entity to table
// modelBuilder.Entity<jenis>().MapToStoredProcedures();
//}
#endregion
}
#region tabels
public class returnpenjualan
{
[Key]
[StringLength(12)]
public string frjb { get; set; }
[Required]
[StringLength(12)]
public string fjb { get; set; }
//THE CAUSE OF ERROR
[Timestamp]
public byte[] RowVersion { get; set; }
[Required]
[StringLength(15)]
public string kepada { get; set; }
[Required]
[StringLength(45)]
public string alamat { get; set; }
[StringLength(45)]
public string ktp { get; set; }
[Required]
public double jumlahreturnpenjualan { get; set; }
[Required]
[StringLength(45)]
public string username { get; set; }
}
#endregion
}
ASK
I've search tutorial and the like for using Timestamp in DataAnnotation and get the same answer for using "Timestamp", is there something iam missing to use "Timestamp"???

I have been search "mysql ef6: timestamp" and using this code for the time being, i don't know this the best solution for my question, is there some another solution, please reply
[Column(TypeName = "timestamp")]
public DateTime RowVersion { get; set; }

Related

ASP.NET Boilerplate - Entity Task Requires Primary Key [duplicate]

I'm training following aspnetboilerplate.com tutorials about developing using their frameworks. I'm stuck at the very first coding point where I have to create a basic table "Task" as stated in the code below.
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Abp.Domain.Entities;
using Abp.Domain.Entities.Auditing;
using Abp.Timing;
namespace WebApp.Tasks
{
[Table("AppTasks")]
public class Task : Entity, IHasCreationTime
{
public const int MaxTitleLength = 256;
public const int MaxDescriptionLength = 64 * 1024; //64KB
[Required]
[StringLength(MaxTitleLength)]
public string Title { get; set; }
[StringLength(MaxDescriptionLength)]
public string Description { get; set; }
public DateTime CreationTime { get; set; }
public TaskState State { get; set; }
public Task()
{
CreationTime = Clock.Now;
State = TaskState.Open;
}
public Task(string title, string description = null)
: this()
{
Title = title;
Description = description;
}
}
public enum TaskState: byte
{
Open = 0,
Completed = 1
}
}
I added the following code in my WebApp DBContext, too.
public class WebAppDbContext : AbpDbContext
{
public DbSet<Task> Tasks { get; set; } //<- This line
public WebAppDbContext(DbContextOptions<WebAppDbContext> options)
: base(options)
{
}
}
The tutorial does not mention any error regarding this code, but every time I make the command
Add-migration "Initial"
in the package manager console, I get this error.
The entity type "Task" requires a primary key to be defined.
I surfed the web for similar errors and each solution I've found does not work for me...
Update #1: I edited the code to this, but the error still remains.
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Abp.Domain.Entities;
using Abp.Domain.Entities.Auditing;
using Abp.Timing;
namespace WebApp.Tasks
{
[Table("AppTasks")]
public class Task : Entity, IHasCreationTime
{
public const int MaxTitleLength = 256;
public const int MaxDescriptionLength = 64 * 1024; //64KB
[Key]
public int Id { get; set; }
[Required]
[StringLength(MaxTitleLength)]
public string Title { get; set; }
[StringLength(MaxDescriptionLength)]
public string Description { get; set; }
public DateTime CreationTime { get; set; }
public TaskState State { get; set; }
public Task()
{
CreationTime = Clock.Now;
State = TaskState.Open;
}
public Task(int id, string title, string description = null)
: this()
{
Id = id;
Title = title;
Description = description;
}
}
public enum TaskState: byte
{
Open = 0,
Completed = 1
}
}
Tutorial link: https://aspnetboilerplate.com/Pages/Documents/Articles/Introduction-With-AspNet-Core-And-Entity-Framework-Core-Part-1/index.html
Update #2: This is the code of WebAppDbContext.cs
using Abp.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;
namespace WebApp.EntityFrameworkCore
{
public class WebAppDbContext : AbpDbContext
{
//Add DbSet properties for your entities...
public DbSet<Task> Tasks { get; set; }
public WebAppDbContext(DbContextOptions<WebAppDbContext> options)
: base(options)
{
}
}
}
I've tried to reproduce your codes on my end and I noticed that the problem that you're dealing with is due to the wrong namespaces in the context WebAppDbContext.
using Abp.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
//using System.Threading.Tasks;//<------------ this line causes the error
using WebApp.Tasks; //<----------- You need to add this namespace.
namespace WebApp.EntityFrameworkCore
{
public class WebAppDbContext : AbpDbContext
{
//Add DbSet properties for your entities...
public DbSet<Task> Tasks { get; set; }
public WebAppDbContext(DbContextOptions<WebAppDbContext> options)
: base(options)
{
}
}
}
The problem is due to a conflict in the naming convention. I would recommend changing the name of the entity to something else to prevent further conflicts in the future.

ASP.NET Core relation is in database but is not retrieved

I am new to ASP.NET Core and I am trying to setup basic relationship with EntityFramework Core. I have a NavigationCategory class that has 1:M relationship with WebPage class. The relationship is understood by my DB (It has a foreign key) but when retrieving the WebPage from repository, it has no NavigationCategory, even though it has NavigationCategoryId set.
public class WebPage : BaseEntity
{
private string _route;
public string Title { get; set; }
public string Body { get; set; }
[ForeignKey("NavigationCategory")]
public long NavigationCategoryId { get; set; }
public NavigationCategory NavigationCategory { get; set; }
public WebPage()
{
}
}
public class NavigationCategory : BaseEntity
{
public string Title { get; set; }
public IEnumerable<WebPage> WebPages { get; set; }
public NavigationCategory()
{
}
}
This is simple BaseEntity:
public class BaseEntity
{
public long Id { get; set; }
}
This is my DB context:
public class AppDataContext : DbContext
{
public DbSet<Employee> Employees { get; set; }
public DbSet<KinderClass> KinderClasses { get; set; }
public DbSet<Feed> Feeds { get; set; }
public DbSet<NavigationCategory> NavigationCategories { get; set; }
public DbSet<WebPage> WebPages { get; set; }
public AppDataContext(DbContextOptions<AppDataContext> options) : base(options)
{
Database.EnsureCreated();
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<WebPage>()
.HasOne(wp => wp.NavigationCategory)
.WithMany(c => c.WebPages)
.HasForeignKey(wp => wp.NavigationCategoryId);
}
}
You need to explicitly include any navigation property you want included when you fetch entities using EF Core. For example, update your query as follows:
var webpage = dbContext.WebPages
.Include(w => w.NavigationCategory)
.FirstOrDefault();
Note, you need these two namespaces, at minimum:
using Microsoft.EntityFrameworkCore;
using System.Linq;
Learn more about loading related data and why lazy loading shouldn't be used in web apps.

LINQ, Using Include Function

I am using EF 6 in Visual Studio 2013. I want to get matching records from a Parent table on behalf of foreign key from Child table.
I have following line of code
var record = db.ChannelFees.Include(x =>x.SubSource).ToList();
Here ChannelFees is the child table in which SubSourceId is foreign key from
SubSource(Parent Table).
Channel Fee Class Looks Like:
using System;
using System.Collections.Generic;
public partial class ChannelFee
{
public virtual SubSource SubSource { get; set; }
public int SubSource_id { get; set; }
public double Fee { get; set; }
public int Id { get; set; }
}
and the SubSource Class
using System;
using System.Collections.Generic;
public partial class SubSource
{
public int Id { get; set; }
public string Description { get; set; }
public string MapName { get; set; }
}
But I am getting the following exception.
A specified Include path is not valid. The EntityType 'FinancialManagmentModel.ChannelFee' does not declare a navigation property with the name 'SubSource'.
What is wrong with it?
I think it should be:
public virtual ICollection<SubSource> SubSource;
You could try with this:
public partial class ChannelFee
{
public virtual ICollection<SubSource> SubSource { get; set; } // Just to enable lazy load
public int Id { get; set; }
public string Description { get; set; }
public string MapName { get; set; }
}
public partial class SubSource
{
public int Id { get; set; }
public string Description { get; set; }
public string MapName { get; set; }
public virtual ChannelFee ChannelFee {get; set; } // Navigation property
}
And usually I also add a Mapping in the context (you can achieve the same result with configuration attributes)
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<SubSource>().HasRequired(t => t.ChannelFee)
.WithMany(t => t.SubSource);
}
Simplest way to solve the problem is to declare a navigation property with the name 'SubSource'. through Annotations
public partial class ChannelFee
{
[ForeignKey("SubSource_id")]
public virtual SubSource SubSource { get; set; }
public int SubSource_id { get; set; }
}
I have resolved the issue at my own. Actually the EF was not generating navigation property in the Model on the behalf of Foreign Key Constraint which I created in SQL, that is why error was occuring.
So I simply deleted the Model and added it again. Problem was solved.

How to Add Attributes to .cs file generated by Entity Framework

I am creating a ASP.net MVC web app and trying to add validation attributes to a ClientsTbl.cs file I have generated from a SQL server using entity framework. I have done scaffolding and created the view and the controller for the Table(Model), but for some reason the scaffold did not recognize the primary key column as a primary key. On top of that it will not let me add attributes in []. I can't even change the field description that appears above the views form text box. How do I do the above in the following class?
namespace Testit.Models
{
using System;
using System.Collections.Generic;
public partial class ClientsTbl
{
public ClientsTbl()
{
this.ProgramClientTbls = new HashSet<ProgramClientTbl>();
}
public int id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int CenterId { get; set; }
public string MiddleName1 { get; set; }
public string MiddleName2 { get; set; }
public System.DateTime DateAdded { get; set; }
public virtual CenterTbl CenterTbl { get; set; }
public virtual ICollection<ProgramClientTbl> ProgramClientTbls { get; set; }
}
}
You can create a metadata class to do that. For example, if Id, FirstName, and LastName are required fields, you can create a new class like below.
public class ClientsTblMetadata
{
[Required()]
public int Id { get; set; }
[Required()]
public string FirstName { get; set; }
[Required()]
public string LastName { get; set; }
}
Then you need to add a new partial class with a MetadataType attribute. Please make sure that this class is located under the same namespace, otherwise it won't work.
namespace Testit.Models
{
[MetadataType(typeof(ClientsTblMetadata))] // you need this line of code.
public partial class ClientsTbl

The operation failed because an index or statistics with name 'IX_AuctionId' already exists on table 'Bids'

This question is related to this question which was never answered. I have a more real world example here though - so hoping for some help.
I have an auction, bid and auctiondetail(a flattened table) class.
I am trying to include my bids in the auction as well as auctiondetail table, auction and auctiondetail have the same PK
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
namespace OnCall.VirtualWarehouse.Data.Models.Auctions
{
using System;
public class AuctionCopy
{
public Guid AuctionCopyId { get; set; }
public virtual Collection<BidCopy> BidCopies { get; set; }
}
public class BidCopy
{
public Guid BidCopyId { get; set; }
public Guid AuctionCopyId { get; set; }
public AuctionCopy AuctionCopy { get; set; }
}
public class AuctionDetailCopy
{
[Key]
public Guid AuctionCopyId { get; set; }
public virtual Collection<BidCopy> BidCopies { get; set; }
}
}
Here's my DBContext:
public class DataContext : DbContext
{
static DataContext()
{
Database.SetInitializer(new DropCreateIfChangeInitializer());
}
public DataContext()
{
Configuration.ProxyCreationEnabled = false;
}
public IDbSet<AuctionCopy> AuctionCopy { get; set; }
public IDbSet<BidCopy> BidCopy { get; set; }
public IDbSet<AuctionDetailCopy> AuctionDetailCopy { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
}
public void Seed(DataContext context)
{
}
}
When generating the database, I get
The operation failed because an index or statistics with name 'IX_AuctionId' already exists on table 'Bids'.
Any ideas how I can get this to work?
The bug come from EF4.3 (and 4.3.1).
It should be fixed for the next release.
Have a look on Unhandled Exception after Upgrading to Entity Framework 4.3.1. They purpose a workaround using migration system.

Categories