NullReferenceException: at DevExpress.Persistent.BaseImpl.EFCore.AuditTrail.AuditDataItem.UpdateDefaultString - entity-framework-core

My PurchaseOrder business object contained
public int? ReceivedByStaffId { get; set; }
[ForeignKey("ReceivedByStaffId")]
public virtual Staff ReceivedBy { get; set; }
And I was using the Audit module.
My Controller was throwing the following error on objectSpace.CommitChanges();
System.Exception: SaveChanges: inner:
ex:System.NullReferenceException: Object reference not set to an instance of an object.
at DevExpress.Persistent.BaseImpl.EFCore.AuditTrail.AuditDataItem.UpdateDefaultString(IEFCoreWeakReference objectForUpdate, EntityEntry entityEntry, Object key)
at DevExpress.Persistent.BaseImpl.EFCore.AuditTrail.AuditDataItem.UpdatePersistentData(List`1 weakReferences)
at DevExpress.Persistent.BaseImpl.EFCore.AuditTrail.AuditDataContainer.AttachAuditData(DbContext dbContext)
at DevExpress.Persistent.BaseImpl.EFCore.AuditTrail.AuditDataContainer.SaveAuditData(DbContext dbContext)
at DevExpress.Persistent.BaseImpl.EFCore.AuditTrail.AuditTrailService.AuditedDbContext_SavedChanges(Object sender, SavedChangesEventArgs e)
at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)
at MyApp2.Module.BusinessObjects.MyAppDbContext.SaveChanges() in D:\dev\MyApp2\MyApp2.Module\BusinessObjects\MyAppDbContext.cs:line 462
stacktrace: at System.Environment.get_StackTrace()
at MyApp2.Module.BusinessObjects.MyAppDbContext.SaveChanges() in D:\dev\MyApp2\MyApp2.Module\BusinessObjects\MyAppDbContext.cs:line 462
at DevExpress.ExpressApp.EFCore.EFCoreObjectSpace.DoCommit()
at DevExpress.EntityFrameworkCore.Security.SecuredEFCoreObjectSpace.DoCommit()
at DevExpress.ExpressApp.BaseObjectSpace.CommitChanges()
at MyApp2.Module.Win.Features.PurchFeature.POStateViewController.actPurchStateMenu_Execute(Object sender, SingleChoiceActionExecuteEventArgs args) in D:\dev\MyApp2\MyApp2.Module.Win\Features\PurchFeature\POStateViewController.cs:line 207
at DevExpress.ExpressApp.Actions.ActionBase.ExecuteCore(Delegate handler, ActionBaseEventArgs eventArgs)
at DevExpress.ExpressApp.Actions.SingleChoiceAction.DoExecute(ChoiceActionItem selectedItem)
at DevExpress.ExpressApp.Templates.ActionControls.Binding.SingleChoiceActionBinding.ActionControl_Execute(Object sender, SingleChoiceActionControlExecuteEventArgs e)
at DevExpress.XtraBars.BarItem.OnClick(BarItemLink link)
at DevExpress.XtraBars.BarItemLink.OnLinkClick()
at DevExpress.XtraBars.BarButtonItemLink.OnLinkAction(BarLinkAction action, Object actionArgs)
at DevExpress.XtraBars.ViewInfo.BarSelectionInfo.UnPressLink(BarItemLink link)
at DevExpress.XtraBars.Controls.CustomLinksControl.OnMouseUp(MouseEventArgs e)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at DevExpress.XtraBars.Controls.CustomControl.WndProc(Message& msg)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, WM msg, IntPtr wparam, IntPtr lparam)
at Interop.User32.DispatchMessageW(MSG& msg)
at Interop.User32.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.Interop.Mso.IMsoComponentManager.FPushMessageLoop(UIntPtr dwComponentID, msoloop uReason, Void* pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(msoloop reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(msoloop reason, ApplicationContext context)
at System.Windows.Forms.Application.Run()
at DevExpress.ExpressApp.Win.WinApplication.Start()
at MyApp2.Win.Program.Main() in D:\dev\MyApp2\MyApp2.Win\Program.cs:line 112
at MyApp2.Module.BusinessObjects.MyAppDbContext.SaveChanges() in D:\dev\MyApp2\MyApp2.Module\BusinessObjects\MyAppDbContext.cs:line 468
at DevExpress.ExpressApp.EFCore.EFCoreObjectSpace.DoCommit()
at DevExpress.EntityFrameworkCore.Security.SecuredEFCoreObjectSpace.DoCommit()
at DevExpress.ExpressApp.BaseObjectSpace.CommitChanges()
at MyApp2.Module.Win.Features.PurchFeature.POStateViewController.actPurchStateMenu_Execute(Object sender, SingleChoiceActionExecuteEventArgs args) in D:\dev\MyApp2\MyApp2.Module.Win\Features\PurchFeature\POStateViewController.cs:line 207

Since the Foreign Key is nullable the navigation property also needs to be nullable
public int? ReceivedByStaffId { get; set; }
[ForeignKey("ReceivedByStaffId")]
public virtual Staff? ReceivedBy { get; set; }

Related

[JAVA]preventing specific duplicate elements from being added to a custom object arraylist

so lets say i have an class called customer with first and last name and username and password
i have another class called bankaccounts with account number and banlance;
and i have an arraylist of customers;
and i have a txt file that i need to read
and it contains the same customer sometimes
how do i make it so that the when its reading if the (first name,lastname,username)are the same
the program wii not add the customer to the list but instead will only add the account to the
existing customer in the list.
sorry if my whole code is a mess but Im so lost in every where and I just want to get this part(the title) right at least please let me know if my question is inappropriate any where i will try my best to edit it
Bob, Mike, bobbmike, Ball!36Hi, 109001, Saving, 140.23, 0.05//good
Bob, Mike, bobbmike, Ball!36Hi, 109002, BasicChecking, 555.23//good
Mouse, Mickey, mickeymouse, MickCool890, ten, Saving, 89, 0.03//wrong numbber
Matt, Benjamin, jamimatt, Kit.24TT, 109201, InterestBearingChecking, 9000.00, 0.06//good
Keller, Helen, kel23hel, Poppins?89, 192911, Retirement, 11198.10//good
Mouse, Minnie, minniemouse, MinnCool19, 192922, Checking, 9000, 0.04//wrong type with interest
Keller, Helen, kel23hel, Poppins?89, 192912, InterestBearingChecking, 11198.10, 0.03//good
Tim, Mary, coolcats, Purr45??, 199122, BasicChecking, 201013.10//good
TheBuilder, Bob, bobbyNice18, 122101, Saving, 0.02//missing password, missing interest
class Customer{
protected String firstName;
protected String lastName;
protected String username;
protected String password;
protected ArrayList<BasicAccount> accounts;
public void setLastName(String ln){this.lastName=ln;}
public String getLastName(){return lastName;}
public void setFirstName(String fn){this.firstName=fn;}
public String getFirstName(){return firstName;}
public void setUsername(String un){this.username=un;}
public String getUserName(){return username;}
public void setPassword(String pw){this.password=pw;}
public String getPassword(){return password;}
public Customer(){}
public Customer(String f,String l,String u,String p) throws Exception{
this.username=f;
this.lastName=l;
this.username=u;
this.password=p;
}
public void addAccount(BasicAccount a){
this.accounts.add(a);
}
public void addAccount(String aType,float balance){
BasicAccount a=new BasicAccount(aType,balance);
}
}
class BasicAccount {
protected static int nextAvailableAccountNumber;
protected AccountType aType;
protected float balance;
protected int accountNum;
enum AccountType {BasicChecking, InterestBearingChecking, Saving, Retirement}
public BasicAccount(){};
public BasicAccount(String f,String l,String u,String p,int an,String type,float b){
}
public BasicAccount(Customer c,int a,String type,float b){
}
public BasicAccount(int a,String type,float b){
this.accountNum=a;
this.aType=AccountType.valueOf(type);
this.balance=b;
nextAvailableAccountNumber=accountNum+1;
}
public BasicAccount(String f,String l, String u,String p,String type,float b){
}
public BasicAccount(Customer c,String type,float b){
}
public BasicAccount(String type,float b){
this.accountNum=nextAvailableAccountNumber;
this.aType=AccountType.valueOf(type);
this.balance=b;
}
public static void main(String[] args)throws IOException {
ArrayList<Customer>cc=new ArrayList<Customer>();
Scanner k=new Scanner(System.in);
out.println("please enter the filename");
String filename=k.nextLine();
File inFile=new File(filename);
Scanner sc=new Scanner(inFile);
String error="";
ArrayList<String> errorLines=new ArrayList<String>();
while(sc.hasNext()){
String line=sc.nextLine();
try{
String []info=line.split(",");
if(info.length==7){
if(info[5].equals("BasicChecking")||info[5].equals("Retirement")){
Customer c=new Customer(info[0],info[1],info[2],info[3]);
BasicAccount act=new BasicAccount(c,Integer.parseInt(info[4]),info[5],Float.parseFloat(info[6]));
String [] user={c.firstName,c.lastName,c.username,c.password};
**for(Customer x:cc){
if(x.contains(c.getFirstName())&&c.getLastName()%%c.getUserName){
x.addAccount(act);
}
else{
c.addAccount(act);
cc.add(c);
}
}**//so if the customer object in the array list contains the same information from the
new Customer c it will only add the account to the x but if its not i will add to c and add
c to the arraylist but this doesn't work
}
else{
//error+="\n Wrong.";
//out.println(error);
}
}
}
catch(Exception e){
error+="\n wrong";
errorLines.add(line);
out.println("wrong data");
}
}
out.println(error);
if(errorLines.size()==0){}
else{
out.println(errorLines);
}
out.println(errorLines);
}
}
Main.java:277: error: cannot find symbol
if(x.contains(c.getFirstName())&&c.getLastName()){
^
symbol: method contains(String)
location: variable x of type Customer
Note: Main.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
1 error
sorry if my whole code is a mess but Im so lost in every where and I just want to get this part(the title) right at least please let me know if my question is inappropriate any where i will try my best to edit it

How the unity container will resolve the registered service

In my code I am trying to log the viewModel name on entry/exit of a viewModel.
My logger is
public interface ILoggerService : ILoggerFacade
{
void LogMessage(string message );
void LogEntry();
void LogExit();
}
public class LoggerService : ILoggerService
{
public void LogEntry()
{
var trace = new StackTrace();
if (trace.FrameCount > 1)
{
string ns = trace.GetFrame(1).GetMethod().DeclaringType.Namespace;
string typeName = trace.GetFrame(1).GetMethod().DeclaringType.Name;
string message = string.Format("{0}.{1}.{2} Entry", ns, typeName,
trace.GetFrame(1).GetMethod().Name);
LogDebug(message, DefaultPriority);
}
}
// Same for LogExit
}
My Bootstrapper
public class Bootstrapper : UnityBootstrapper
{
protected override void ConfigureContainer()
{
base.ConfigureContainer();
Container.RegisterInstance<ILoggerService>(_logger);
}
protected override ILoggerFacade CreateLogger()
{
_logger = new LoggerService();
return _logger;
}
}
My ViewModel & Model are
public class HomeViewModel
{
private readonly ILoggerService _loggerService;
private readonly HomeModel _model;
public HomeViewModel(HomeModel model, ILoggerService logger)
{
logger.LogEntry();
_model = model;
_loggerService = logger;
// Do some other stuff here.
logger.LogExit();
}
}
public class HomeModel
{
private ILoggerService _logger;
public HomeModel(ILoggerService logger)
{
logger.LogEntry();
_logger = logger;
logger.LogExit();
}
}
Error I got
Cat[Critical} Sev[Critical] Pri[100] Framework Time:[ 2016-09-22 13:33:39.860] Shisha.exe PId: 22220 ThreadId:7428
#### An exception occurred while initializing module 'MainModule'.
- The exception message was: Resolution of the dependency failed, type = "Modules.Main.Views.HomeView", name = "(none)".
Exception occurred while: Calling constructor Modules.Main.Models.HomeModel(Services.Logging.Interface.ILoggerService logger).
Exception is: NullReferenceException - Object reference not set to an instance of an object.
-----------------------------------------------
At the time of the exception, the container was:
Resolving Modules.Main.Views.HomeView,(none)
Resolving parameter "viewModel" of constructor Modules.Main.Views.HomeView(Modules.Main.ViewModels.HomeViewModel viewModel)
Resolving Modules.Main.ViewModels.HomeViewModel,(none)
Resolving parameter "model" of constructor Modules.Main.ViewModels.HomeViewModel(Modules.Main.Models.HomeModel model, Microsoft.Practices.Prism.Regions.IRegionManager regionManager, Microsoft.Practices.Prism.Events.IEventAggregator eventAggregator, Services.Dialogs.Interface.IDialogService dialogService, Services.Logging.Interface.ILoggerService logger, Services.Localisation.Interfaces.ITranslator translator)
Resolving Modules.Main.Models.HomeModel,(none)
Calling constructor Modules.Main.Models.HomeModel(Services.Logging.Interface.ILoggerService logger)
- The Assembly that the module was trying to be loaded from was:Modules.Main, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
Check the InnerException property of the exception for more information. If the exception occurred while creating an object in a DI container, you can exception.GetRootException() to help locate the root cause of the problem.
at Services.Logging.LoggerService.LogCritical(String message, Int32 priority) in C:\Projects\Utilities\DotNet\Services\Services.Logging\LoggerService.cs:line 257
at Services.Logging.LoggerService.LogCritical(String message) in C:\Projects\Utilities\DotNet\Services\Services.Logging\LoggerService.cs:line 250
at Shisha.Bootstrapper.InitializeModules() in C:\Projects\Shisha\Application\Shisha\Bootstrapper.cs:line 85
at Microsoft.Practices.Prism.UnityExtensions.UnityBootstrapper.Run(Boolean runWithDefaultConfiguration)
at Shisha.App.Application_Startup(Object sender, StartupEventArgs e) in C:\Projects\Shisha\Application\Shisha\App.xaml.cs:line 39
at System.Windows.Application.OnStartup(StartupEventArgs e)
at System.Windows.Application.<.ctor>b__1_0(Object unused)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.DispatcherOperation.InvokeImpl()
at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at MS.Internal.CulturePreservingExecutionContext.Run(CulturePreservingExecutionContext executionContext, ContextCallback callback, Object state)
at System.Windows.Threading.DispatcherOperation.Invoke()
at System.Windows.Threading.Dispatcher.ProcessQueue()
at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
at System.Windows.Application.RunDispatcher(Object ignore)
at System.Windows.Application.RunInternal(Window window)
at System.Windows.Application.Run(Window window)
at MyApp.App.Main() in C:\Projects\Shisha\Application\Shisha\obj\x86\Release\App.g.cs:line 0
I Googled and debugged ( by adding logs ) a lot finally came to know that it is the
"trace.GetFrame(1).GetMethod().DeclaringType.Namespace;"
that is failing..
It working fine in 'Debug' mode ( because of PDB file ) but is failing in 'Release' mode.
Instead of resolving the logger from constructor if we use
Resolve<ILoggerService>(),
it is working fine.
It is not clear for me how _container.Resolve() got the MethodBase information and 'resolving from constructor' didn't.
Can anyone explain me what is the difference between these two.
OR
Am I completely missing something?
It seems the compiler is converting the constructor to inline constructor.
By using [MethodImpl(MethodImplOptions.NoInlining)] and telling the compiler not to inline is working fine.
[MethodImpl(MethodImplOptions.NoInlining)]
public class HomeModel
{
private ILoggerService _logger;
public HomeModel(ILoggerService logger)
{
logger.LogEntry();
_logger = logger;
logger.LogExit();
}
}

Xamarin PCL connected to WCF Service throws System.typeload exception on save

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?

autofac registergeneric error "sequence contains no element"

Using Autofac, I tried to use my generic type :
public interface IRepository<T> where T : class
{
void Add(T entity);
void Update(T entity);
void Delete(T entity);
void Delete(Expression<Func<T, bool>> where);
T GetById(long Id);
T GetById(string Id);
T Get(Expression<Func<T, bool>> where);
IEnumerable<T> GetAll();
IEnumerable<T> GetMany(Expression<Func<T, bool>> where);
}
to register my generic class :
public abstract class RepositoryBase<T> where T : class
{
private iMOSSContainer dataContext;
private readonly IDbSet<T> dbset;
protected RepositoryBase()
{
DatabaseFactory = new DatabaseFactory();
dbset = DataContext.Set<T>();
}
protected RepositoryBase(IDatabaseFactory databaseFactory)
{
DatabaseFactory = databaseFactory;
dbset = DataContext.Set<T>();
}
protected IDatabaseFactory DatabaseFactory
{
get;
private set;
}
protected iMOSSContainer DataContext
{
get { return dataContext ?? (dataContext = DatabaseFactory.Get()); }
}
public virtual void Add(T entity)
{
dbset.Add(entity);
}
public virtual void Update(T entity)
{
dbset.Attach(entity);
dataContext.Entry(entity).State = EntityState.Modified;
}
public virtual void Delete(T entity)
{
dbset.Remove(entity);
}
public virtual void Delete(Expression<Func<T, bool>> where)
{
IEnumerable<T> objects = dbset.Where<T>(where).AsEnumerable();
foreach (T obj in objects)
dbset.Remove(obj);
}
public virtual T GetById(long id)
{
return dbset.Find(id);
}
public virtual T GetById(string id)
{
return dbset.Find(id);
}
public virtual IEnumerable<T> GetAll()
{
return dbset.ToList();
}
public virtual IEnumerable<T> GetMany(Expression<Func<T, bool>> where)
{
return dbset.Where(where).ToList();
}
public T Get(Expression<Func<T, bool>> where)
{
return dbset.Where(where).FirstOrDefault<T>();
}
}
this way :
var builder = new ContainerBuilder();
builder.RegisterGeneric(typeof(RepositoryBase<>)).As(typeof(IRepository<>)); //.InstancePerLifetimeScope();
Container = builder.Build();
And returns an error "sequence contains no element" when building a container.
Did i do something wrong with the code? I already tried to search for an answer to no avail. So, your help would be pretty much appreciated.
Ok, then i changed the RepositoryBase class like this :
public class RepositoryBase<T> : IRepository<T> where T : class
{
private iMOSSContainer dataContext;
private readonly IDbSet<T> dbset;
public RepositoryBase()
{
DatabaseFactory = new DatabaseFactory();
dbset = DataContext.Set<T>();
}
So :
i use the "iRepository" interface (and move the "where T : class"
statement at the end of the line)
i remove the "abstract" class (because it leads to another error)
set the default constructor to "public" (because it leads to another
error, as well)
And everything is working good right now.
Your RepositoryBase type is abstract, therefore it can't be registered. You need to register non-abstract types. I'm guessing what you're intending to do is register all subtypes of RepositoryBase.

Exception, with two references in base class with Entity Framework 5

I had this problem in a project, since I don't want to give the whole domain scope, I've tried to simplify the classes as much as possible.
Basically I have a base class BaseClass, where two properties are referencing a a class that is Extending BaseClass => ClassA
It works if I remove ClassB.
It works if I remove one of the two references.
It works when I don't extend ClassA from the BaseClass
But not in this constellation:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using System.Threading;
namespace EFTestbed
{
public abstract class BaseClass
{
public int Id { get; set; }
public ClassA ClassA1 { get; set; }
public ClassA ClassA2 { get; set; }
}
public class ClassA : BaseClass
{
public string TitleA { get; set; }
}
public class ClassB : BaseClass
{
public string TitleB { get; set; }
}
public class Context : DbContext
{
public DbSet<ClassA> ClassAs { get; set; }
public DbSet<ClassB> ClassBs { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ClassA>()
.HasOptional(e => e.ClassA1).WithOptionalDependent();
modelBuilder.Entity<ClassA>()
.HasOptional(e => e.ClassA2).WithOptionalDependent();
modelBuilder.Entity<ClassB>()
.HasOptional(e => e.ClassA1).WithOptionalDependent();
modelBuilder.Entity<ClassB>()
.HasOptional(e => e.ClassA2).WithOptionalDependent();
}
}
public class Program
{
static void Main(string[] args)
{
Thread.CurrentThread.CurrentCulture =
Thread.CurrentThread.CurrentUICulture =
new System.Globalization.CultureInfo("en-GB");
System.Console.WriteLine("Creating & Updating database...");
Database.SetInitializer(new DropCreateDatabaseAlways<Context>());
using (var context = new Context())
{
context.ClassAs.Add(new ClassA() { TitleA = "Test1" });
System.Console.WriteLine(
string.Format("Number of objects written to the database: {0}",
context.SaveChanges()));
}
System.Console.Write("Press Enter to continue...");
System.Console.ReadLine();
}
}
}
I always get this Exception "Sequence contains more than one element"
How do I get it to work?
Here is the stack trace of the Exception:
at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source)
at System.Data.Entity.ModelConfiguration.Configuration.Properties.Navigation.NavigationPropertyConfiguration.ConfigureDependentBehavior(EdmAssociationType associationType, EdmModel model, EntityTypeConfiguration entityTypeConfiguration)
at System.Data.Entity.ModelConfiguration.Configuration.Properties.Navigation.NavigationPropertyConfiguration.Configure(EdmNavigationProperty navigationProperty, EdmModel model, EntityTypeConfiguration entityTypeConfiguration)
at System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.ConfigureAssociations(EdmEntityType entityType, EdmModel model)
at System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.Configure(EdmEntityType entityType, EdmModel model)
at System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.ConfigureEntities(EdmModel model)
at System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.Configure(EdmModel model)
at System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo)
at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
at System.Data.Entity.Internal.InternalContext.Initialize()
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
at System.Data.Entity.Internal.Linq.InternalSet`1.ActOnSet(Action action, EntityState newState, Object entity, String methodName)
at System.Data.Entity.Internal.Linq.InternalSet`1.Add(Object entity)
at System.Data.Entity.DbSet`1.Add(TEntity entity)
at EFTestbed.Program.Main(String[] args) in d:\users\sasp1de\documents\visual studio 2010\Projects\EFTestbed\EFTestbed\TestEF\Program.cs:line 54
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
This is now fixed in the latest version of EF:
http://entityframework.codeplex.com/workitem/546