I had a project with ef6 and npgsql 3.2, all worked perfect. But when i updated npgsql to 4.0 and attempt to save entity i got an exception:
"InnerException": {
"ClassName": "System.Data.Entity.Core.UpdateException",
"Message": "An error occurred while updating the entries. See the inner exception for details.",
"Data": null,
"InnerException": {
"ClassName": "System.NotSupportedException",
"Message": "Parameters with NpgsqlDbType.Unknown are no longer supported. If you're writing enums as strings, see the section on unmapped enums in the documentation.",
"Data": null,
"InnerException": null,
"HelpURL": null,
"StackTraceString": " в Npgsql.TypeHandlers.UnknownTypeHandler.ValidateObjectAndGetLength(Object value, NpgsqlLengthCache& lengthCache, NpgsqlParameter parameter)\r\n в Npgsql.NpgsqlParameter.ValidateAndGetLength()\r\n в Npgsql.NpgsqlCommand.ValidateParameters()\r\n в Npgsql.NpgsqlCommand.<ExecuteDbDataReader>d__101.MoveNext()\r\n--- Конец трассировка стека из предыдущего расположения, где возникло исключение ---\r\n в System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n в System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n в System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.<ExecuteAsync>d__0.MoveNext()\r\n--- Конец трассировка стека из предыдущего расположения, где возникло исключение ---\r\n в System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n в System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n в System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.<UpdateAsync>d__0.MoveNext()",
"RemoteStackTraceString": null,
"RemoteStackIndex": 0,
"ExceptionMethod": "8\nValidateObjectAndGetLength\nNpgsql, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5d8b90d52f46fda7\nNpgsql.TypeHandlers.UnknownTypeHandler\nInt32 ValidateObjectAndGetLength(System.Object, Npgsql.NpgsqlLengthCache ByRef, Npgsql.NpgsqlParameter)",
"HResult": -2146233067,
"Source": "Npgsql",
"WatsonBuckets": null
},
"HelpURL": null,
"StackTraceString": " в System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.<UpdateAsync>d__0.MoveNext()\r\n--- Конец трассировка стека из предыдущего расположения, где возникло исключение ---\r\n в System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n в System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n в System.Data.Entity.Core.Objects.ObjectContext.<ExecuteInTransactionAsync>d__3d`1.MoveNext()\r\n--- Конец трассировка стека из предыдущего расположения, где возникло исключение ---\r\n в System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n в System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n в System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStoreAsync>d__39.MoveNext()\r\n--- Конец трассировка стека из предыдущего расположения, где возникло исключение ---\r\n в System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n в System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n в System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesInternalAsync>d__31.MoveNext()",
"RemoteStackTraceString": null,
"RemoteStackIndex": 0,
"ExceptionMethod": "8\nMoveNext\nEntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\nSystem.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator+<UpdateAsync>d__0\nVoid MoveNext()",
"HResult": -2146233087,
"Source": "EntityFramework",
"WatsonBuckets": null
}
Model code:
[Table("entities")]
public class EntityDto
{
[Column("id")]
[JsonProperty("id")]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
[Column("alias")]
[Index(IsUnique = true)]
public string Alias { get; set; }
[Column("name")]
public string Name { get; set; }
[Column("display")]
public string Display { get; set; }
[Column("dbtable")]
public string DbTable { get; set; }
[Column("assembly")]
public long Assembly { get; set; }
[Column("autogenerated")]
public bool Autogenerated { get; set; }
}
Table of entity was generated perfect by automigration.
At the same time, data selection works correctly.
Whats wrong?
Thanks for reporting this, it's an actual behavior change in Npgsql 4 that didn't take into account the EF6 provider. Can you please open an issue about this on http://github.com/Npgsql/npgsql.
EDIT: Reverted the behavior change, everything should work again in 4.0.0-preview2 which should be released very soon.
Related
I don't understand why I'm getting a syntax error when this line of code executes:
return ((IObjectContextAdapter)this).ObjectContext.ExecuteStoreQuery<Kitti_getProductGroupDetail_Result>("Kitti_getProductGroupDetail #ProductGroupId", #params);
Here is the whole method:
public virtual ObjectResult<Kitti_getProductGroupDetail_Result> Kitti_getProductGroupDetail(Guid ProductGroupId)
{
var #params = new SqlParameter[]
{
new SqlParameter("ProductGroupId", ProductGroupId)
};
return ((IObjectContextAdapter)this).ObjectContext.ExecuteStoreQuery<Kitti_getProductGroupDetail_Result>("Kitti_getProductGroupDetail #ProductGroupId", #params);
}
Here is the calling method:
public System.Collections.Generic.IEnumerable<ProductDetail> getProductDetailsFromSP(Guid ProductGroupId)
{
System.Collections.Generic.List<ProductDetail> productDetailList = new System.Collections.Generic.List<ProductDetail>();
using (var context = new EFDbContext())
{
var result = context.Kitti_getProductGroupDetail(ProductGroupId);
foreach (Kitti_getProductGroupDetail_Result res in result)
{
ProductDetail productDetail = new ProductDetail();
productDetail.ProductId = res.productid;
productDetail.SizeId = res.sizeid;
productDetail.SizeDescription = res.sizedescription;
productDetail.SizeRank = res.sizerank;
productDetail.ColorId = res.colorid;
productDetail.ColorDescription = res.colordescription;
productDetail.ColorRank = res.colorrank;
productDetail.QuantityRemainingInStock = res.quantityremaininginstock;
productDetail.ProductGroupId = res.productgroupid;
productDetail.ProductGroupName = "ProductGroupName is currently not in the stored procedure or in EF";
productDetail.Description = res.description;
productDetailList.Add(productDetail);
}
}
return productDetailList;
}
The result object:
public partial class Kitti_getProductGroupDetail_Result
{
public System.Guid productid { get; set; }
public System.Guid productgroupid { get; set; }
public string description { get; set; }
public decimal price { get; set; }
public Nullable<System.Guid> colorid { get; set; }
public string colordescription { get; set; }
public int colorrank { get; set; }
public Nullable<System.Guid> sizeid { get; set; }
public string sizedescription { get; set; }
public int sizerank { get; set; }
public int quantityremaininginstock { get; set; }
public string productname { get; set; }
public string imagesrc { get; set; }
}
Finally here is my stored procedure:
ALTER PROCEDURE [dbo].[Kitti_getProductGroupDetail]
#ProductGroupId uniqueidentifier
-- Insert statements for procedure here
SELECT product.ProductId as 'productid', product.ProductGroupId as 'productgroupid', product.[Description] as 'description'
, product.Price as 'price', product.ColorId as 'colorid', color.ColorDescription as 'colordescription', color.ColorRank as 'colorrank',
product.SizeId as 'sizeid', size.SizeDescription as 'sizedescription', size.SizeRank as 'sizerank', product.QuantityRemainingInStock as 'quantityremaininginstock',
product.Name as 'productname', product.ProductImageSrc as 'imagesrc'
FROM dbo.Product product
INNER JOIN dbo.Color color
on color.ColorId = product.ColorId
INNER JOIN dbo.Size size
on size.SizeId = product.SizeId
INNER JOIN dbo.ProductGroup productgroup
on productgroup.ProductGroupId = product.ProductGroupId
WHERE product.ProductGroupId = #ProductGroupId
AND product.QuantityRemainingInStock > 0
ProductGroupId is definitely getting populated. What doesn't EF like about my code? I have a similar method that does not require a parameter to execute the stored procedure - it works fine
// this works just fine
public virtual ObjectResult<Kitti_getProductDetailsAndCategory_Result> Kitti_getProductDetailsAndCategory()
{
return ((IObjectContextAdapter)this).ObjectContext.ExecuteStoreQuery<Kitti_getProductDetailsAndCategory_Result>("Kitti_getProductDetailsAndCategory");
//ExecuteFunction changed to ExecuteStoreQuery
}
stack trace:
Incorrect syntax near 'Kitti_getProductGroupDetail'.
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.Data.SqlClient.SqlException: Incorrect syntax near 'Kitti_getProductGroupDetail'.
Source Error:
Line 40: };
Line 41:
Line 42: return ((IObjectContextAdapter)this).ObjectContext.ExecuteStoreQuery("Kitti_getProductGroupDetail #ProductGroupId", #params);
Line 43: }
Line 44:
Source File: C:\Concrete\EFDbContext.cs Line: 42
Stack Trace:
[SqlException (0x80131904): Incorrect syntax near 'Kitti_getProductGroupDetail'.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) +2444082
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) +5775560
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +285
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +4169
System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() +58
System.Data.SqlClient.SqlDataReader.get_MetaData() +89
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption) +409
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest) +2127
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry) +911
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +64
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +240
System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +41
System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) +12
System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<Reader>b__c(DbCommand t, DbCommandInterceptionContext1 c) +14
System.Data.Entity.Infrastructure.Interception.InternalDispatcher1.Dispatch(TTarget target, Func3 operation, TInterceptionContext interceptionContext, Action3 executing, Action3 executed) +72
System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext) +402
System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior) +166
System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) +12
System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreQueryInternal(String commandText, String entitySetName, ExecutionOptions executionOptions, Object[] parameters) +266
System.Data.Entity.Core.Objects.<>c__DisplayClass691.<ExecuteStoreQueryReliably>b__68() +44
System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction(Func1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) +288
System.Data.Entity.Core.Objects.<>c__DisplayClass691.<ExecuteStoreQueryReliably>b__67() +167
System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Func1 operation) +190
System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreQueryReliably(String commandText, String entitySetName, ExecutionOptions executionOptions, Object[] parameters) +462
System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreQuery(String commandText, Object[] parameters) +83
KittiCutieFashion.Domain.Concrete.EFDbContext.Kitti_getProductGroupDetail(Guid ProductGroupId) in C:\KittiCutieFashion\KittiCutieFashion.Domain\Concrete\EFDbContext.cs:42
KittiCutieFashion.Domain.Concrete.EFDbContext.getProductDetailsFromSP(Guid ProductGroupId) in C:\KittiCutieFashion\KittiCutieFashion.Domain\Concrete\EFDbContext.cs:82
KittiCutieFashion.Domain.Concrete.EFProductDetailRepository.get_ProductDetail() in C:\KittiCutieFashion\KittiCutieFashion.Domain\Concrete\EFProductDetailRepository.cs:33
KittiCutieFashion.WebUI.Controllers.ProductDetailController.ProductDetailView(String returnUrl) in C:\KittiCutieFashion\KittiCutieFashion.WebUI\Controllers\ProductDetailController.cs:43
lambda_method(Closure , ControllerBase , Object[] ) +103
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) +157
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) +27
System.Web.Mvc.Async.<>c.b__9_0(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +22
System.Web.Mvc.Async.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
System.Web.Mvc.Async.AsyncInvocationWithFilters.b__11_0() +50
System.Web.Mvc.Async.<>c__DisplayClass11_1.b__2() +228
System.Web.Mvc.Async.<>c__DisplayClass7_0.b__1(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
System.Web.Mvc.Async.<>c__DisplayClass3_6.b__3() +35
System.Web.Mvc.Async.<>c__DisplayClass3_1.b__5(IAsyncResult asyncResult) +100
System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
System.Web.Mvc.<>c.b__152_1(IAsyncResult asyncResult, ExecuteCoreState innerState) +11
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +45
System.Web.Mvc.<>c.b__151_2(IAsyncResult asyncResult, Controller controller) +13
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +22
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.<>c.b__20_1(IAsyncResult asyncResult, ProcessRequestState innerState) +28
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9748493
System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +48
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +159
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.7.2558.0
The version of sql server I am using happens to be 2005 not sure if that has anything to do with it.
Whenever I try to connect to the database I get this exception
Unhandled Exception: System.Data.SqlClient.SqlException: Cannot open database "TrackTvDb" requested by the login. The login failed.
Login failed for user 'DESKTOP-MTHC289\hristo.kolev'.
at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionPool.WaitForPendingOpen()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.<OpenAsync>d__31.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable.AsyncEnumerator.<MoveNext>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.EntityFrameworkCore.Query.AsyncQueryMethodProvider.<GetResult>d__16`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.EntityFrameworkCore.Query.Internal.TaskResultAsyncEnumerable`1.Enumerator.<MoveNext>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.<MoveNext>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at ManualTesting.EntryPint.<MainAsync>d__1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at ManualTesting.EntryPint.Main(String[] args)
I have SqlServer 2016 and this is a .Net Core application.
Here is the DbContext
namespace TrackTv
{
using Microsoft.EntityFrameworkCore;
using TrackTv.Models;
using TrackTv.Models.Joint;
public class TrackTvDbContext : DbContext
{
public DbSet<Actor> Actors { get; set; }
public DbSet<Episode> Episodes { get; set; }
public DbSet<Genre> Genres { get; set; }
public DbSet<Network> Networks { get; set; }
public DbSet<Show> Shows { get; set; }
public DbSet<User> Users { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder builder)
{
builder.UseSqlServer(#"Server=.;Database=TrackTvDb;Trusted_Connection=True;MultipleActiveResultSets=True;");
base.OnConfiguring(builder);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// ShowsUsers
modelBuilder.Entity<ShowsUsers>().HasKey(t => new
{
t.UserId,
t.ShowId
});
modelBuilder.Entity<ShowsUsers>().HasOne(t => t.User).WithMany(user => user.ShowsUsers).HasForeignKey(t => t.UserId);
modelBuilder.Entity<ShowsUsers>().HasOne(t => t.Show).WithMany(show => show.ShowsUsers).HasForeignKey(t => t.ShowId);
// ShowsActors
modelBuilder.Entity<ShowsActors>().HasKey(t => new
{
t.ShowId,
t.ActorId
});
modelBuilder.Entity<ShowsActors>().HasOne(t => t.Show).WithMany(show => show.ShowsActors).HasForeignKey(t => t.ShowId);
modelBuilder.Entity<ShowsActors>().HasOne(t => t.Actor).WithMany(actor => actor.ShowsActors).HasForeignKey(t => t.ActorId);
// ShowsGenres
modelBuilder.Entity<ShowsGenres>().HasKey(t => new
{
t.ShowId,
t.GenreId
});
modelBuilder.Entity<ShowsGenres>().HasOne(t => t.Show).WithMany(show => show.ShowsGenres).HasForeignKey(t => t.ShowId);
modelBuilder.Entity<ShowsGenres>().HasOne(t => t.Genre).WithMany(genre => genre.ShowsGenres).HasForeignKey(t => t.GenreId);
}
}
}
My project.json
{
"version": "1.0.0-*",
"buildOptions": {
"emitEntryPoint": true
},
"frameworks": {
"netcoreapp1.0": {
"dependencies": {
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.0.1"
},
"TrackTv": "*",
"Microsoft.EntityFrameworkCore.SqlServer": "1.0.1"
}
}
}
}
I can login with Management Studio like this:
I have several other working .NET applications that access that instance of SqlServer with EF6.
Can you please try adding Integrated Security attribute in you connection string?
builder.UseSqlServer(#"Server=.;Database=TrackTvDb;Trusted_Connection=True;MultipleActiveResultSets=True;Integrated Security=true");
I have the following WCF Service contract:
[ServiceContract]
public interface IGMesDataService
{
[OperationContract]
List<HejMessage> GetHejMessages();
[OperationContract]
void SaveHejMessage(HejMessage msg);
}
The type HejMessage is an Entity and I have added its attributes through the text templates and the result is as follows:
[DataContract]
public partial class HejMessage
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string Text { get; set; }
[DataMember]
public double Latitude { get; set; }
[DataMember]
public double Longitude { get; set; }
}
The code in the xamarin.forms pcl is as follows:
in the app constructor:
GMesDataServiceClient client = new GMesDataServiceClient();
client.GetHejMessagesCompleted += Client_GetHejMessagesCompleted;
client.GetHejMessagesAsync();
and the event handler:
private void Client_GetHejMessagesCompleted(object sender, GetHejMessagesCompletedEventArgs e)
{
foreach(HejMessage msg in e.Result)
AllHejMessages.Add(msg);
}
On a "post message" button click:
private void PostButton_Clicked(object sender, EventArgs e)
{
HejMessage msg = new HejMessage
{
Text = "Awesome item",
Latitude = 100,
Longitude = 100
};
AllHejMessages.Add(msg);
GMesDataServiceClient client = new GMesDataServiceClient();
client.SaveHejMessageCompleted += Client_SaveHejMessageCompleted;
client.SaveHejMessageAsync(msg);
}
the completed event here just catches the exception for me.
When I run the wcf service locally everything works smashingly. When I deploy the service the GetHejMessages call still works but the SaveHejMessage returns the following System.TypeLoadException:
Message:
{"Inheritance security rules violated while overriding member:
'System.Data.Entity.Utilities.TaskExtensions+CultureAwaiter`1<T>.UnsafeOnCompleted(System.Action)'.
Security accessibility of the overriding method must match the security accessibility of the method being overriden."}
Stack Trace:
at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternalAsync(SaveOptions options, Boolean executeInExistingTransaction, CancellationToken cancellationToken)\r\n
at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesAsync(SaveOptions options, CancellationToken cancellationToken)\r\n
at System.Data.Entity.Internal.InternalContext.SaveChangesAsync(CancellationToken cancellationToken)\r\n
at System.Data.Entity.Internal.LazyInternalContext.SaveChangesAsync(CancellationToken cancellationToken)\r\n
at System.Data.Entity.DbContext.SaveChangesAsync(CancellationToken cancellationToken)\r\n
at System.Data.Entity.DbContext.SaveChangesAsync()\r\n
at GMesService.GMesDataService.SaveHejMessage(HejMessage msg) in C:\\Users\\Eric\\documents\\visual studio 2015\\Projects\\GMes\\GMesService\\GMesDataService.cs:line 22\r\n
at SyncInvokeSaveHejMessage(Object , Object[] , Object[] )\r\n
at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)\r\n
at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)\r\n
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)\r\n
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage41(MessageRpc& rpc)\r\n
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc)\r\n
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc)\r\n
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc& rpc)\r\n
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc& rpc)\r\n
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage11(MessageRpc& rpc)\r\n
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc& rpc)\r\n
at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)"
Any Ideas?
I have a WebAPI that I have Cors enabled.
My webAPI references a Class library that I do a lot of the processing in.
calls between the WebAPI and Class library and also some calls inside the class library are
throwing this error...
{"Message":"An error has occurred.","ExceptionMessage":"Object reference not set to an instance of an object.",
"ExceptionType":"System.NullReferenceException","StackTrace":"
at RCIS.MappingServices.WebAPI.Utilities.SQL.SQLInsertObjects(Int32 TypeMapId, Int32 GrowerId, Int32 CropYear, String NAME, String SHAPE, String CREATED_BY, String CREATED_DATETIME, String MODIFIED_BY, String MODIFIED_DATETIME, String IsDELETED)\r\n
at RCIS.MappingServices.WebAPI.Controllers.PostObjectsController.GET(String TypeMapId, String GrowerId, String CropYear, String NAME, String SHAPE)\r\n
at lambda_method(Closure , Object , Object[] )\r\n
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)\r\n
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext,
IDictionary`2 arguments, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n
at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n
at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n
at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()"}
This Only seems to be happening when calling the class library from the server (i.e.) I enter a URL into Chrome calling the WebAPI method and get this error back.
If I use all primitive types in the WebAPI and In the class library I get a success message back.
If you have any questions please let me know.
Any help on this would be greatly appreciated I have been trying to solve this for 2 days!!!
Make sure the only thing you are passing is string values.
Make an ErrorHelper:
public class ErrorHelper : IHttpActionResult
{
private HttpRequestMessage Request { get; }
private HttpStatusCode statusCode;
private string message;
public ErrorHelper(HttpRequestMessage request, HttpStatusCode statusCode, string message)
{
this.Request = request;
this.statusCode = statusCode;
this.message = message;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
return Task.FromResult(Request.CreateErrorResponse(statusCode, message));
}
}
Then call it like this:
public IHttpActionResult Get(int id)
{
try
{
var person = _repository.GetPersonId(id);
if (person == null)
{
return NotFound();
}
return Ok(person);
}
catch (Exception ex)
{
return new ErrorHelper(Request, HttpStatusCode.InternalServerError, ex.ToString());
}
}
This will give you the Exception details. You probably haven't got a component installed on the Server, like a Database Driver or something like that.
Whenever I enter text in the outputText by clicking speak out for the first time no exception happens, everything gets updated in the database but when I click the speak out button for the second time I get the following exception.
1) Home.xhtml
</div>
<div style="width:100%;background-color:#EEEEEE;">
<h:panelGrid columns="2">
<h:form>
<h:outputText value="Speak Out"/><br/>
<h:outputText value="Share whats in your mind.!" style="color:#aaaaaa;font-size:x-small;"/>
<p:inputTextarea name="content" id="sharetext" cols="60" rows="2" onclick="this.value='';" value="#{statusBean.status.statusmsg}" style="text-size:small;" /><br/>
<p:commandButton type="submit" value="Speak Out" action="#{statusBean.save}" ajax="false" styleClass="buttonstyle"/><br/>
</h:form>
<h:form>
<h:outputText value="Pic Out"/><br/>
<p:fileUpload fileUploadListener="#{statusBean.handleFileUpload}"/>
<h:outputText value="Share whats in your mind through an image.!" style="color:#aaaaaa;font-size:x-small;"/>
<p:inputTextarea name="content" id="sharetext" cols="60" rows="2" onclick="this.value='';" value="#{statusBean.status.picstatusdesc}" style="text-size:small;" /><br/>
<p:commandButton type="submit" value="Pic Out" action="#{statusBean.picSave}" ajax="false" styleClass="buttonstyle"/><br/>
</h:form>
</h:panelGrid>
</div>
2) StatusBean.java
public class StatusBean {
Date d;
Comment comment;
Status status;
private EntityManager em;
private UploadedFile uploadedFile;
public Comment getComment() {
return comment;
}
public void setComment(Comment comment) {
this.comment = comment;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public StatusBean() {
d = new Date();
comment = new Comment();
status = new Status();
EntityManagerFactory emf = Persistence
.createEntityManagerFactory("FreeBird");
em = emf.createEntityManager();
}
public String save() {
FacesContext context = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) context.getExternalContext()
.getSession(true);
User user = (User) session.getAttribute("userdet");
status.setEmail(user.getEmail());
status.setStatusBy(user.getFirstName());
status.setTimeMillis(d.getTime());
status.setPicture(user.getImage());
System.out.println("status save called");
em.getTransaction().begin();
em.persist(status);
em.getTransaction().commit();
session.isNew();
return "success";
}
public String picSave() {
FacesContext context = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) context.getExternalContext()
.getSession(true);
User user = (User) session.getAttribute("userdet");
status.setEmail(user.getEmail());
status.setStatusBy(user.getFirstName());
status.setTimeMillis(d.getTime());
status.setPicture(user.getImage());
System.out.println("picstatus save called");
em.getTransaction().begin();
em.persist(status);
em.getTransaction().commit();
session.isNew();
return "success";
}
public void handleFileUpload(FileUploadEvent e) {
System.out.println("file handler called");
uploadedFile = e.getFile();
String fileName = uploadedFile.getFileName();
fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
FacesContext context = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) context.getExternalContext()
.getSession(true);
System.out.println(fileName);
try {
ServletContext ctx = (ServletContext) FacesContext
.getCurrentInstance().getExternalContext().getContext();
String imagesPath = ctx.getRealPath("images");
FileOutputStream fos = new FileOutputStream(imagesPath
+ "/statusPicture/" + fileName);
fos.write(uploadedFile.getContents());
fos.flush();
fos.close();
status.setPicstatus(fileName);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
3) Status Entity Class
#Entity
public class Status implements Serializable,Comparable<Status> {
private static final long serialVersionUID = 1L;
#Id
private int statusId;
private String email;
private String picstatus;
private String picstatusdesc;
private String picture;
private String statusBy;
private String statusmsg;
private long timeMillis;
public Status() {
}
public int getStatusId() {
return this.statusId;
}
public void setStatusId(int statusId) {
this.statusId = statusId;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPicstatus() {
return this.picstatus;
}
public void setPicstatus(String picstatus) {
this.picstatus = picstatus;
}
public String getPicstatusdesc() {
return this.picstatusdesc;
}
public void setPicstatusdesc(String picstatusdesc) {
this.picstatusdesc = picstatusdesc;
}
public String getPicture() {
return this.picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
public String getStatusBy() {
return this.statusBy;
}
public void setStatusBy(String statusBy) {
this.statusBy = statusBy;
}
public String getStatusmsg() {
return this.statusmsg;
}
public void setStatusmsg(String statusmsg) {
this.statusmsg = statusmsg;
}
public long getTimeMillis() {
return this.timeMillis;
}
public void setTimeMillis(long l) {
this.timeMillis = l;
}
#Override
public int compareTo(Status o) {
return (int) (o.getTimeMillis()-this.getTimeMillis());
}
}
4) StackTrace
WARNING: #{statusBean.save}: javax.persistence.RollbackException: Exception [EclipseLink-7197] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.ValidationException
Exception Description: Null or zero primary key encountered in unit of work clone [com.entity.Status#1523582], primary key [0]. Set descriptors IdValidation or the "eclipselink.id-validation" property.
javax.faces.FacesException: #{statusBean.save}: javax.persistence.RollbackException: Exception [EclipseLink-7197] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.ValidationException
Exception Description: Null or zero primary key encountered in unit of work clone [com.entity.Status#1523582], primary key [0]. Set descriptors IdValidation or the "eclipselink.id-validation" property.
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1550)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:343)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:79)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:722)
Caused by: javax.faces.el.EvaluationException: javax.persistence.RollbackException: Exception [EclipseLink-7197] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.ValidationException
Exception Description: Null or zero primary key encountered in unit of work clone [com.entity.Status#1523582], primary key [0]. Set descriptors IdValidation or the "eclipselink.id-validation" property.
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
... 36 more
Caused by: javax.persistence.RollbackException: Exception [EclipseLink-7197] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.ValidationException
Exception Description: Null or zero primary key encountered in unit of work clone [com.entity.Status#1523582], primary key [0]. Set descriptors IdValidation or the "eclipselink.id-validation" property.
at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.commitInternal(EntityTransactionImpl.java:102)
at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.commit(EntityTransactionImpl.java:63)
at com.bean.StatusBean.save(StatusBean.java:80)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.sun.el.parser.AstValue.invoke(AstValue.java:254)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:302)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
... 37 more
Caused by: Exception [EclipseLink-7197] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.ValidationException
Exception Description: Null or zero primary key encountered in unit of work clone [com.entity.Status#1523582], primary key [0]. Set descriptors IdValidation or the "eclipselink.id-validation" property.
at org.eclipse.persistence.exceptions.ValidationException.nullPrimaryKeyInUnitOfWorkClone(ValidationException.java:1439)
at org.eclipse.persistence.descriptors.changetracking.DeferredChangeDetectionPolicy.calculateChanges(DeferredChangeDetectionPolicy.java:107)
at org.eclipse.persistence.descriptors.changetracking.DeferredChangeDetectionPolicy.calculateChangesForExistingObject(DeferredChangeDetectionPolicy.java:54)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.calculateChanges(UnitOfWorkImpl.java:643)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabaseWithChangeSet(UnitOfWorkImpl.java:1490)
at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.commitRootUnitOfWork(RepeatableWriteUnitOfWork.java:267)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitAndResume(UnitOfWorkImpl.java:1143)
at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.commitInternal(EntityTransactionImpl.java:84)
... 47 more
WARNING: StandardWrapperValve[Faces Servlet]: PWC1406: Servlet.service() for servlet Faces Servlet threw exception
Local Exception Stack:
Exception [EclipseLink-7197] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.ValidationException
Exception Description: Null or zero primary key encountered in unit of work clone [com.entity.Status#1523582], primary key [0]. Set descriptors IdValidation or the "eclipselink.id-validation" property.
at org.eclipse.persistence.exceptions.ValidationException.nullPrimaryKeyInUnitOfWorkClone(ValidationException.java:1439)
at org.eclipse.persistence.descriptors.changetracking.DeferredChangeDetectionPolicy.calculateChanges(DeferredChangeDetectionPolicy.java:107)
at org.eclipse.persistence.descriptors.changetracking.DeferredChangeDetectionPolicy.calculateChangesForExistingObject(DeferredChangeDetectionPolicy.java:54)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.calculateChanges(UnitOfWorkImpl.java:643)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabaseWithChangeSet(UnitOfWorkImpl.java:1490)
at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.commitRootUnitOfWork(RepeatableWriteUnitOfWork.java:267)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitAndResume(UnitOfWorkImpl.java:1143)
at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.commitInternal(EntityTransactionImpl.java:84)
at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.commit(EntityTransactionImpl.java:63)
at com.bean.StatusBean.save(StatusBean.java:80)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.sun.el.parser.AstValue.invoke(AstValue.java:254)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:302)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1550)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:343)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:79)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:722)
log file rotation...
I don't understand why it works the first time, but just like Nicolas Labrot I can't see you setting your primary key and that is why you get an Exception that your primary key is null.
If you set your key somewhere else, check if it might be 0. Eclipselink does not support 0 as a primary key if you don't set the following property in your persistence.xml, you get that Exception.
<property name="eclipselink.allow-zero-id" value="true"/>
This property simply tells EclipseLink to treat '0' as a valid primary key instead of null.
Property eclipselink.allow-zero-id is deprecated, so you should use eclipselink.id-validation to define which primary key components values are considered invalid.
<property name="eclipselink.id-validation" value="NULL"/>
See: https://www.eclipse.org/eclipselink/documentation/2.4/jpa/extensions/p_id_validation.htm