Specified table does not exist - c#

I'm searching for an answer to this question. I don't know where is the problem. Visual Studio does not see any problem or error, but when I run program and try to add something to database, application crashes and VS tell me that my table does not exist. That event is for adding something.
This is my code:
private void addBtn_Click(object sender, RoutedEventArgs e)
{
using (WpisyDataContext BazaDanych = new WpisyDataContext(strConnectionString))
{
if (!BazaDanych.DatabaseExists())
{
BazaDanych.CreateDatabase();
MessageBox.Show("BazaDanych Database Created Successfully!!!");
}
Wpis newWpis = new Wpis
{
RecordID = index_box.Text,
NameRec = name_box.Text.ToString(),
BeneficiaryRec = beneficiary_box.Text.ToString(),
PriceRec = price_box.Text.ToString(),
DeadlineRec = deadline_box.Text.ToString(),
DescriptionRec = description_box.Text.ToString()
};
BazaDanych.Wpisy.InsertOnSubmit(newWpis);
BazaDanych.SubmitChanges();
MessageBox.Show("Recoed Added Successfully!!!");
if (NavigationService.CanGoBack)
{
NavigationService.GoBack();
}
}
}
}
This is the table code (Wpis.cs):
using System.Data.Linq.Mapping;
namespace ********
{
[Table]
public class Wpis
{
[Column(IsPrimaryKey = true, IsDbGenerated = true)]
public string RecordID
{
get;
set;
}
[Column(CanBeNull = true)]
public string NameRec
{
get;
set;
}
[Column(CanBeNull = true)]
public string BeneficiaryRec
{
get;
set;
}
[Column(CanBeNull = true)]
public string PriceRec
{
get;
set;
}
[Column(CanBeNull = true)]
public string DeadlineRec
{
get;
set;
}
[Column(CanBeNull = true)]
public string DescriptionRec
{
get;
set;
}
}
}
And this is the data context (WpisyDataContext.cs):
using System.Data.Linq;
namespace *************
{
public class WpisyDataContext : DataContext
{
public WpisyDataContext(string connectionString)
: base(connectionString)
{
}
public Table<Wpis> Wpisy
{
get
{
return this.GetTable<Wpis>();
}
}
}
}
This is connection string:
public static string strConnectionString = #"Data Source=isostore:/DevDB.sdf";
Please guys, I don't have any more patience. Thanks.

When you use CreateDatabase(), please check whether .Net has created the database table as your Entity. Because EntityFramework create table with Plural name and Entity is created with singular name.
Check whether the created table name is as expected.

Related

Error when try to insert value in database with NPoco

I am using this example from Umbraco docs and when i try to save values to the database table i am getting this error:
Cannot insert the value NULL into column 'Id', table 'petapoco.dbo.BlogComments'; column does not allow nulls. INSERT fails. The statement has been terminated.
Also, after table is created and i check it in database, I can see that primary key and autoincrement option is not set for id field.
And this is how i insert values:
public class Class1 : IUserComposer
{
public void Compose(Composition composition)
{
composition.Components().Append<SubscribeToContentServiceSavingComponent>();
}
public class SubscribeToContentServiceSavingComponent : IComponent
{
public void Initialize()
{
MemberService.Saved += MemberService_Saving;
}
public void Terminate()
{
}
private void MemberService_Saving(IMemberService sender, SaveEventArgs<IMember> e)
{
foreach (IMember member in e.SavedEntities)
{
var blogPostToAdd = new BlogCommentSchema();
blogPostToAdd.BlogPostUmbracoId = member.Id;
blogPostToAdd.Name = member.Name;
blogPostToAdd.Email = member.Name;
blogPostToAdd.Website = member.Name;
blogPostToAdd.Message = member.Name;
using (var scope = Current.ScopeProvider.CreateScope(autoComplete:true))
{
var database = scope.Database;
// use database
scope.Database.Insert<BlogCommentSchema>(blogPostToAdd);
scope.Complete();
}
}
}
}
}
Good guy on Umbraco forum solved my problem. This is the missing part in my class:
[PrimaryKeyColumn(AutoIncrement = true, IdentitySeed = 1)]
So my class finally should look like this:
[TableName("BlogComments")]
[PrimaryKey("Id", AutoIncrement = true)]
[ExplicitColumns]
public class BlogCommentSchema
{
[PrimaryKeyColumn(AutoIncrement = true, IdentitySeed = 1)]
[Column("Id")]
public int Id { get; set; }
[Column("BlogPostUmbracoId")]
public int BlogPostUmbracoId { get; set; }
[Column("Name")]
public string Name { get; set; }
[Column("Email")]
public string Email { get; set; }
[Column("Website")]
public string Website { get; set; }
[Column("Message")]
[SpecialDbType(SpecialDbTypes.NTEXT)]
public string Message { get; set; }
}
}

How to drop table in Xamarin from sqlite database

I am unable to drop tables completely from sqLite database in XAMARIN using command db.DropTable<tablename>. It gets dropped at first but appears again every time I restart the application. Also I have multiple tables with the same name and I need to drop them all. What should I do?
I am developing an android application in Visual Studio using XAMARIN and C#.
Unfortunately I created many tables with the same name. Now I need to drop them.
I am using following code to create tables and database:-
namespace Test
{
[Table("OrderDetails")]
public class OrderDetails
{
[PrimaryKey, AutoIncrement, Column("_id")]
public int Id { get; set; }
[MaxLength(50)]
public string payeename { get; set; }
[MaxLength(100)]
public string commodity { get; set; }
public int give { get; set; }
public int take { get; set; }
public DateTime date { get; set; }
}
[Activity(Label = "Test", MainLauncher = true)]
public class MainActivity : Activity
{
[Table("Items")]
public class PayeeMaster
{
[PrimaryKey, AutoIncrement, Column("_id")]
public int Id { get; set; }
[MaxLength(8)]
public string FirstName { get; set; }
[MaxLength(8)]
public string LastName { get; set; }
}
SQLiteConnection db;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
CreateDatabase();
}
public bool ifExists_Table(string tablename)
{
SQLiteCommand command = db.CreateCommand("SELECT COUNT(1) FROM SQLITE_MASTER WHERE TYPE = #TYPE AND NAME = #NAME");
command.Bind("#TYPE", "table");
command.Bind("#NAME", tablename);
int result = command.ExecuteQuery<int>();
return (result > 0);
}
public void CreateDatabase() {
try
{
string dbPath = Path.Combine(
System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal),
"Master.db3");
db = new SQLiteConnection(dbPath);
}
catch (IOException ex)
{
var reason = string.Format("The database failed to create -
reason {0}", ex.Message);
}
if (!ifExists_Table("PayeeMaster"))
{
db.CreateTable<PayeeMaster>();
}
else
{
var count = db.Table<PayeeMaster>().Count();
}
if (!ifExists_Table("OrderDetails"))
{
db.CreateTable<OrderDetails>();
}
else {
var count = db.Table<OrderDetails>().Count();
}
}
}
I finally understand the problem, sorry for the confusion.
First of all - doing Table<T>().Count() doesn't actually check for table existence, but instead checks if the table contains any rows.
To actually check if the table exists, you will have to do an actual SQL query:
private bool DoesTableExist(string name)
{
    SQLiteCommand command = _connection.CreateCommand("SELECT COUNT(1) FROM SQLITE_MASTER WHERE TYPE = #TYPE AND NAME = #NAME");
    command.Bind("#TYPE", "table");
    command.Bind("#NAME", name);
    int result = command.ExecuteScalar<int>();
    return (result > 0);
}

Entity Framework Core error not seen before Class.TempProperty is of type 'object' which is not supported by current database provider

I am using Entity Framework Core code-first with fluent API entity configurations, in an ASP .NET MVC Core application. My code currently compiles, but when I run add-migration in the Package Manager Console, it gives the error below:
The property 'Exam.TempId' is of type 'object' which is not supported
by current database provider. Either change the property CLR type or
manually configure the database type for it.
Searching Google for this error yields no results. Can anybody here help please?
"Exam" is a class in my domain model, but it doesn't have a "TempId" property so I guess that's something that Entity Framework is adding. It does have an "Id" property, but the type is int, not object.
I'll start by sharing the Exam class and the Exam configuration class. I can share more code if required. I'd be really grateful for any advice you can provide to resolve the problem.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
namespace MySite.Core.Models
{
public class Exam : ActivatableEntity
{
private int _numberOfQuestionsToBeAttempted;
private Exam()
{
Topics = new Collection<Topic>();
}
public Exam(IUser createdByUser,
string name,
string description,
double timeAllowedInMinutes,
bool shuffleTopicsTogether = true) :
base(createdByUser)
{
Name = name;
Description = description;
Topics = new Collection<Topic>();
TimeAllowedInMinutes = timeAllowedInMinutes;
ShuffleTopicsTogether = shuffleTopicsTogether;
}
public string Name { get; private set; }
public string Description { get; private set; }
public double TimeAllowedInMinutes { get; private set; }
public bool ShuffleTopicsTogether { get; private set; }
public IEnumerable<Question> PossibleQuestions
{
get
{
return Topics.SelectMany(t => t.PossibleQuestions);
}
}
public int NumberOfQuestionsToBeAttempted
{
get
{
if (_numberOfQuestionsToBeAttempted != 0) return _numberOfQuestionsToBeAttempted;
foreach (Topic topic in Topics)
{
_numberOfQuestionsToBeAttempted += topic.NumberOfQuestionsToBeAttempted;
}
return _numberOfQuestionsToBeAttempted;
}
}
public IEnumerable<Topic> Topics { get; }
public void Update(IUser updatedByUser, string name, string description, double timeAllowedInMinutes, bool shuffleTopicsTogether = true)
{
Name = name ?? throw new ArgumentNullException(nameof(name));
Description = description;
TimeAllowedInMinutes = timeAllowedInMinutes;
ShuffleTopicsTogether = shuffleTopicsTogether;
Update(updatedByUser);
}
}
}
Exam configuration class
using MySite.Core.Models;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace MySite.Persistence.EntityConfiguration
{
public class ExamConfiguration
{
public ExamConfiguration(EntityTypeBuilder<Exam> entityBuilder)
{
entityBuilder.HasKey(e => e.Id);
entityBuilder.HasOne(e => (ApplicationUser)e.CreatedByUser)
.WithMany()
.HasForeignKey(e => e.CreatedByUserId)
.OnDelete(DeleteBehavior.SetNull);
entityBuilder.HasOne(e => (ApplicationUser)e.LastUpdatedByUser)
.WithMany()
.HasForeignKey(e => e.LastUpdatedByUserId)
.OnDelete(DeleteBehavior.SetNull);
entityBuilder.Property(e => e.Name).IsRequired().HasMaxLength(50);
entityBuilder.Property(e => e.Description).IsRequired().HasMaxLength(250);
entityBuilder.HasMany(e => e.Topics)
.WithOne(t => t.Exam).OnDelete(DeleteBehavior.Cascade);
}
}
}
As requested by posters, I'm adding the code for the base classes below:
using System;
namespace MySite.Core.Models
{
public abstract class ActivatableEntity :
UpdatableCreatableEntity,
IActivatable
{
protected ActivatableEntity() { }
protected ActivatableEntity(IUser createdByUser) : base(createdByUser) { }
public int? LastActivatedByUserId { get; private set; }
public IUser LastActivatedByUser { get; private set; }
public DateTime? WhenLastActivated { get; private set; }
public int? LastDeactivatedByUserId { get; private set; }
public IUser LastDeactivatedByUser { get; private set; }
public DateTime? WhenLastDeactivated { get; private set; }
public bool IsActive { get; private set; }
protected virtual void Activate(IUser activatedByUser)
{
LastActivatedByUser = activatedByUser ?? throw new ArgumentNullException(nameof(activatedByUser));
LastActivatedByUserId = activatedByUser.Id;
WhenLastActivated = DateTime.Now;
IsActive = true;
}
protected virtual void Deactivate(IUser deactivatedByUser)
{
LastDeactivatedByUser = deactivatedByUser ?? throw new ArgumentNullException(nameof(deactivatedByUser));
LastDeactivatedByUserId = deactivatedByUser.Id;
WhenLastDeactivated = DateTime.Now;
IsActive = false;
}
}
public abstract class UpdatableCreatableEntity :
CreatableEntity,
IUpdatable
{
protected UpdatableCreatableEntity() { }
protected UpdatableCreatableEntity(IUser createdByUser) : base(createdByUser) { }
public int? LastUpdatedByUserId { get; private set; }
public IUser LastUpdatedByUser { get; private set; }
public DateTime? WhenLastUpdated { get; private set; }
protected virtual void Update(IUser updatedByUser)
{
LastUpdatedByUser = updatedByUser ?? throw new ArgumentNullException(nameof(updatedByUser));
LastUpdatedByUserId = updatedByUser.Id;
WhenLastUpdated = DateTime.Now;
}
}
public abstract class CreatableEntity :
IIdentifiable,
ICreatable
{
protected CreatableEntity() { }
protected CreatableEntity(IUser createdByUser)
{
CreatedByUser = createdByUser ?? throw new ArgumentNullException(nameof(createdByUser));
CreatedByUserId = createdByUser.Id;
WhenCreated = DateTime.Now;
}
public int Id { get; private set; }
public int? CreatedByUserId { get; private set; }
public DateTime WhenCreated { get; private set; }
public IUser CreatedByUser { get; private set; }
}
}
I faced same problem and it confused me a lot. But luckily I was using version control, so I was able to trace reasons of the issue.
For me it was many-to-many relation entity model with constructor that assigns values to fields. I was relying to Visual Studio to generate properties for me automatically, and VS did poor job not detecting type of the property that later became a key.
VS created property of type object, which is too generic and hardly could be translated into underlying database abstractions. Hence the error.
I agree, quite not descriptive, hope they will fix that in future versions.
So try to search for properties of object type and check, are they used as keys, if yes, try to replace them with specific types supported by your database provider.
Reported error for developers: #9817.

Simplest way to populate class from query in C# [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
I want to populate a class from a query.
this is an example class:
private class TVChannelObject
{
public string number { get; set; }
public string title { get; set; }
public string favoriteChannel { get; set; }
public string description { get; set; }
public string packageid { get; set; }
public string format { get; set; }
}
How can I fill this class from an database query? Is there any way to do this automatically as far as table column names are identical to class attributes?
As others have suggested, an ORM is the best way to go. You could, however, implement this functionality using reflection:
using System.Reflection;
void Main()
{
var connectionString = "...";
var records = new Query(connectionString).SqlQuery<TVChannel>("select top 10 * from TVChannel");
}
private class TVChannel
{
public string number { get; set; }
public string title { get; set; }
public string favoriteChannel { get; set; }
public string description { get; set; }
public string packageid { get; set; }
public string format { get; set; }
}
public class Query
{
private readonly string _connectionString;
public Query(string connectionString)
{
_connectionString = connectionString;
}
public List<T> SqlQuery<T>(string query)
{
var result = new List<T>();
using (var connection = new SqlConnection(_connectionString))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = query;
using (var reader = command.ExecuteReader())
{
var columns = Enumerable.Range(0, reader.FieldCount).Select(reader.GetName).ToArray();
var properties = typeof(T).GetProperties();
while (reader.Read())
{
var data = new object[reader.FieldCount];
reader.GetValues(data);
var instance = (T)Activator.CreateInstance(typeof(T));
for (var i = 0; i < data.Length; ++i)
{
if (data[i] == DBNull.Value)
{
data[i] = null;
}
var property = properties.SingleOrDefault(x => x.Name.Equals(columns[i], StringComparison.InvariantCultureIgnoreCase));
if (property != null)
{
property.SetValue(instance, Convert.ChangeType(data[i], property.PropertyType));
}
}
result.Add(instance);
}
}
}
}
return result;
}
}
You can use Linq to SQL with C#. With Linq, you can easily map your tables with C# classes and then query or populate them with a few lines of code.
Check out this link: Insert rows with Linq to SQL
EDIT:
The first thing you need to do is to map your class to your database table. Like this:
[Table(Name = "tvchannel")] // Here you put the name of the table in your database.
private class TVChannelObject
{
Column(Name = "number", IsPrimaryKey = true)] // Here, number is the name of the column in the database and it is the primary key of the table.
public string number { get; set; }
[Column(Name = "title", CanBeNull = true)] // If the field is nullable, then you can set it on CanBeNull property.
public string title { get; set; }
[Column(Name = "channelFavorite", CanBeNull = true)] // Note that you can have a field in the table with a different name than the property in your class.
public string favoriteChannel { get; set; }
[Column(Name = "desc", CanBeNull = true)]
public string description { get; set; }
[Column(Name = "package", CanBeNull = false)]
public string packageid { get; set; }
[Column(Name = "format", CanBeNull = false)]
public string format { get; set; }
}
After mapping your database with the corresponding fields for your table, you can now build a method in your class to insert a row:
public void InsertTvChannel()
{
// DataContext takes a connection string.
string connString = "Data Source=SomeServer;Initial Catalog=SomeDB;User ID=joe;Password=swordfish" //example
DataContext db = new DataContext(connString);
// Create a new object tv channel to insert
TVChannelObject channel = new TVChannelObject();
channel.number = 1;
channel.title = "Some title";
channel.favoriteChannel = "some channel";
channel.description = "some description";
channel.packageid = "the package id";
channel.format = "the format";
// Now that you have the object for the new channel, let's insert it:
db.TVChannelObjects.InsertOnSubmit(channel); //this just adds to a collection. It is a prepare to insert.
// Submit the change to the database.
try
{
db.SubmitChanges();
}
catch (Exception e)
{
Console.WriteLine(e);
// If you face errors, you can handle it with some code here.
// ...
// Try again.
db.SubmitChanges();
}
}
This code should work, with just a few adjustments. Now you have an example to insert with a Linq mapping.
Use ORM like entity framework.
For your simplicity , follow this link
www.codeproject.com/Articles/739164/Entity-Framework-Tutorial-for-Beginners

Error inserting record with entity framework

I am sorry if it has already been answered but I can't find any solution. Here is my (little) problem. Also all my apologies if the terms I use are approximate, I am far from being a skilled C# developer
Note that I think my problem is similar to this one Entity Framework validation error for missing field, but it's not missing?
I have a table "Tweets" with a tweet_id field (bigint) which is my primary key.
I use the following class to load the table :
class TwitterDbContext : DbContext
{
public TwitterDbContext() : base("Twitter")
{
}
public DbSet<Stream> Streams { get; set; }
public DbSet<StreamParameter> StreamParameters { get; set; }
public DbSet<Tweet> Tweets { get; set; }
}
public class Tweet
{
public Tweet()
{
}
[Key]
public long tweet_id { get; set; }
public string tweet { get; set; }
public long creator { get; set; }
public double latitude { get; set; }
public double longitude { get; set; }
public string language { get; set; }
public DateTime created_at { get; set; }
public DateTime registered_at { get; set; }
public long? in_reply_to { get; set; }
public bool retweeted { get; set; }
}
I have an other class to store within the code execution all the fields used by the Tweet table. For the need here, let's imagine I manually create it that way
private void Test_Button_Click(object sender, RoutedEventArgs e)
{
Twts twtReceived = new Twts();
twtReceived.tweet_id = 1;
twtReceived.tweet = "test";
twtReceived.creator = 1;
twtReceived.latitude = -1;
twtReceived.longitude = -1;
twtReceived.language = "a";
twtReceived.created_at = DateTime.Now;
twtReceived.registered_at = DateTime.Now;
twtReceived.in_reply_to = 1;
twtReceived.retweeted = true;
AddTweet(twtReceived);
}
Now here is the AddTweet method
static public void AddTweet(Twts twtReceived)
{
try
{
// update the tweet data in the database
using (var TwitterDb = new TwitterDbContext())
{
Tweet twt = new Tweet()
{
tweet_id = twtReceived.tweet_id,
tweet = twtReceived.tweet,
creator = twtReceived.creator,
longitude = twtReceived.longitude,
latitude = twtReceived.latitude,
language = twtReceived.language,
created_at = twtReceived.created_at,
registered_at = twtReceived.registered_at,
in_reply_to = twtReceived.in_reply_to,
retweeted = twtReceived.retweeted
};
TwitterDb.Tweets.Add(twt);
TwitterDb.SaveChanges();
}
}
catch(Exception ex)
{
MessageBox.Show(ex.InnerException.ToString());
}
}
I constantly have the same error message:
Cannot insert the value NULL into column 'tweet_id', table
'Twitter.dbo.Tweets'; column does not allow nulls. INSERT fails.
The thing is that when I spy on "TwitterDb.Tweets.Local" after TwitterDb.Tweets.Add(twt); I correctly have tweet_id set to 1.
Any idea where is the issue?
Try marking your tweet_id field with following (instead of just [Key]), if this is a primary key column where you want to provide values yourself
[Required, Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
If it is an auto-increment, then remove explicit assignments to this field and mark it as 'Identity' instead:
[Required, Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]

Categories

Resources