Error about initializing database - entity framework 6 - c#

Getting error saving the object in the database stage .I'm waiting for a suggestion for a solution from those who have information on the subject.
I checked my connection strings actually dont have much idea to try.
public void SaveNew(Person p)
{
using (var context = new FeatureContext())
{
context.People.Add(p);// error line
context.SaveChanges();
}
}
}
exception
System.Data.DataException: 'An exception occurred while initializing the database. See the InnerException for details.'
SqlException: Cannot attach the file 'C:\Users\ertug.dilek\source\repos\AddFeatures\WebApplication1\App_Data\AddFeatures.Model.FeatureContext.mdf'
as database 'AddFeatures.Model.FeatureContext'.

Related

Entity Framework exception suddenly

I have this code in my backend:
using (var context = new Db_EnforcementEntities())
{
try
{
DbContextHelper.SetContextConfig(context, false);
VW_ENF_TviotOnePercentage[] test = context.VW_ENF_TviotOnePercentage.ToArray();
}
}
where VW_ENF_TviotOnePercentage is a view which already exists in my EDMX file.
The above code worked perfectly up until several days ago, and I could fetch records which are identical to the records I could see in the database.
For some reason, when I get to the code now, I get an exception:
Object reference not set to an instance of an object
The stack trace points to:
at System.Object.GetType()
at System.Data.EntityKey.ValidateTypeOfKeyValue
What could go wrong in the database to cause this error?

SQLite issue with insert not unique

I have a button in my project that inserts a record into my SQLite database.
but there is an issue cus I have unique index so if the insert is a dup it will error out and quit the function.. how can I prevent from showing an error and quitting?
SQLite error (2067): abort at 11 in [INSERT INTO my_success VALUES('123456')]: column myids is not unique
A first chance exception of type 'System.Data.SQLite.SQLiteException' occurred in System.Data.SQLite.dll
Probably not the best solution, but you should be able to catch the exception:
try
{
// put your SQLite insert code here...
}
catch(System.Exception)
{
}

Object reference not set to an instance of an object. BitShuva

Hi I've downloaded some source code and I'm having some major issues with it straight out of the box. I've not been able to get an answer from the developer and I've not seen anyone else ask this question, but I've looked and looked and looked and I've no idea what's going wrong.
I keep getting this error:
Server Error in '/' Application.
Object reference not set to an instance of an object.
Description:
An unhandled exception occurred during the execution of the current web request.
Please review the stack trace for more information about the error and where it originated in the code.
Exception Details:
System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 157: // Expected ID is standard Raven ID: "songs/4321"
Line 158: const string expectedIdPrefix = "songs/";
Line 159: if (song.Id.StartsWith(expectedIdPrefix, StringComparison.OrdinalIgnoreCase))
Line 160: {
Line 161: throw new ArgumentException("ID wasn't in the expected format.");
Visual Studio highlights this bit of code. (denoted by ** **)
using (var session = Get.A<IDocumentStore>().OpenSession())
{
var songFiles = Directory
.EnumerateFiles(Server.MapPath("~/content/sample/music"), "*.mp3")
.Select(f => new
{
Song = new Song(Path.GetFileName(f)),
FilePath = f
})
.ToArray();
songFiles.ForEach(async f => **await f.Song.UploadMp3ToCdn(f.FilePath));**
if (!session.Query<Song>().Any())
{
songFiles.ForEach(s => session.Store(s));
session.SaveChanges();
}
}
Have you tried inspecting songFiles within the debugger? The error seems to suggest that either f.Song or f.FilePath is null/uninitialised.
Found the issue, it's trying to upload music to the CDN specified in the web.config file, and it's looking for the ID of the song. The ID must be generated by Raven database first, and it's trying to pull the ID prior.
Issue Fixed.

Customize Sql Exception message in catch

I ´m doing a form where the user can Insert/Delete/Add entities. I´m using Winforms c# and entity framework 4.
Ok, the user can delete objects. Now, those objects can be referenced by other entities, so if the user wants to delete it, he will get an exception.
I catch that exception so as to show him a message that says that that object is begin used in other objects.
The exception I got is (UpdateException). But this exception can be raised if there is an update issue too. Is there any way to get the error code from Sql using this exception? Because I do have the error code that throws when this happens.
If I use SqlException I can check its number, but that's not the exception I´m receiving.
Do you mean you want to see the full exception or you want the user to the see the exception?
If you want to the see exception, you could write it to a text file:
try
{
// do something
}
catch(SQLException sqlex)
{
using (var file = new StreamWriter(#"C:\Users\Home\Desktop\sqlException.txt"))
{
file.WriteLine(sqlex.ToString());
}
}
catch(Exception e)
{
using (var file = new StreamWriter(#"C:\Users\Home\Desktop\generalException.txt"))
{
file.WriteLine(e.ToString());
}
}
This will write the exception to a text file on your desktop (change directories as appropriate).

Entity Framework with SQLite exception: The underlying provider failed on Commit

I'm using the Entity Framework (.NET 4.0) with SQLite as the underlying database and I get an exception when I try to commit some changes to the database:
The underlying provider failed on Commit.
The stack trace is:
System.Data.EntityException: The underlying provider failed on Commit. ---> System.Data.SQLite.SQLiteException: The database file is locked
database is locked
at System.Data.SQLite.SQLite3.Step(SQLiteStatement stmt)
at System.Data.SQLite.SQLiteDataReader.NextResult()
at System.Data.SQLite.SQLiteDataReader..ctor(SQLiteCommand cmd, CommandBehavi
or behave)
at System.Data.SQLite.SQLiteCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.SQLite.SQLiteCommand.ExecuteNonQuery()
at System.Data.SQLite.SQLiteTransaction.Commit()
at System.Data.EntityClient.EntityTransaction.Commit()
--- End of inner exception stack trace ---
at System.Data.EntityClient.EntityTransaction.Commit()
at System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options)
at MySystem.MySystemService.UpdateFollowersAndUsers() in C:\Path\To\MySystem\MySystemService.cs:line 295
My code is pretty simple:
// Gets more followers for the competitor and updates the database
List<Follower> moreFollowers = GetMoreFollowers(competitor);
// Add the new followers to the database
using (MySystemEntities db = new MySystemEntities())
{
try
{
foreach (Follower f in moreFollowers)
{
db.AddToFollowers(f);
}
db.SaveChanges();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
This snippet of code is inside MyService, it comes in with a batch of 5,000 followers and it's getting the above exception. However, when I pull the same snippet of code out into the Main function and just manually add a few followers, then it no longer throws the exception and the followers are successfully added to my database. Apparently the database file is locked, what may be causing this issue?
I just found out the answer in another SO question: 'The database file is locked' with System.Data.SQLite
Ironically, the OP answers his own question too :).

Categories