The entity type [NAME] is not part of the model for the current context. When compile in Release - entity-framework-5

After generate my EDMX Model, and develop usual code do manage objects on the database with entityframework5, everyting works fine (selets, inserts, update and deletes) on Debug Mode.
The absolute same code when i go to deploy or run my webapp on Release Mode, on runtime i get an exception telling that a entity is not found: "The entity type [NAME] is not part of the model for the current context".
Is there something that i need to do, when my app runs on release mode?
thanks in advance for your help

Please verify that you have your variables assigned even with a null.
ProviderClass p = null;
Example:
[Debug mode Ok, Release error]
public class XPTO
{
ProviderClass p;
public start()
{
p = new ProviderClass();
}
public ProviderClass GetBy(long id)
{
return p.GetList<ProviderClass>()
.Where(x => x.IDXPTO == id)
.FirstOrDefault()
.ToDomain();
}
}
[Debug = ok, Release = ok]
public class XPTO
{
ProviderClass p = null;
public start()
{
p = new ProviderClass();
}
public ProviderClass GetBy(long id)
{
return p.GetList<ProviderClass>()
.Where(x => x.IDXPTO == id)
.FirstOrDefault()
.ToDomain();
}
}

Related

Add contacts to Marketing list on CRM2011

I'm trying to build a Workflow that add a Contact to a marketing list.
Everything seems to be fine, but when the code finishes firing, and I go to the marketing list -> members the contact is not in the list.
public class ContactToMList : CodeActivity
{
[Input("Contatto")]
[ReferenceTarget("contact")]
public InArgument<EntityReference> contact { get; set; }
[Input("Marketing List")]
[ReferenceTarget("list")]
public InArgument<EntityReference> MList { get; set; }
[Input("Inserimento")]
public InArgument<bool> inserimento { get; set; }
bool action = false;
private static IOrganizationService myService = null;
private static Log_Entity log = new Log_Entity(string.Empty, myService);
protected override void Execute(CodeActivityContext executionContext)
{
try
{
ITracingService tracingService = executionContext.GetExtension<ITracingService>();
// Create the context
IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
// Create the Organiztion service
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
myService = service;
log.WriteLog("");
// Get the target entity from the context
Entity target = (Entity)context.InputParameters["Target"];
Guid contactiId = contact.Get<EntityReference>(executionContext).Id;
Guid ListId = MList.Get<EntityReference>(executionContext).Id;
bool insert = inserimento.Get<bool>(executionContext);
// Prepare DataContext by using AutoGenerated cs file
XrmDataContext datacontext = new XrmDataContext(service);
var MyContact = (from c in datacontext.ContactSet where c.ContactId == contactiId select c.Id).ToArray();
var MyList = (from l in datacontext.ListSet where l.Id == ListId select l).ToList().FirstOrDefault();
// tutti i membri della lista di marketing
var members = (from m in datacontext.ListMemberSet where m.ListId.Id == MyList.ListId select m.EntityId.Id).ToArray();
foreach (Guid id in members)
if (MyContact.FirstOrDefault() == id)
action = true;
if (insert && !action)
{
AddListMembersListRequest AddMemberRequest = new AddListMembersListRequest();
AddMemberRequest.ListId = ListId;
AddMemberRequest.MemberIds = MyContact;
// Use AddListMembersListReponse to get information about the request execution
AddListMembersListResponse AddMemberResponse = service.Execute(AddMemberRequest) as AddListMembersListResponse;
//service.Update(MyList);
}
else if (!insert && action)
{
RemoveMemberListRequest RemoveMemberRequest = new RemoveMemberListRequest();
RemoveMemberRequest.ListId = ListId;
RemoveMemberRequest.EntityId = MyContact.FirstOrDefault();
// Use AddListMembersListReponse to get information about the request execution
RemoveMemberListResponse RemoveMemberResponse = service.Execute(RemoveMemberRequest) as RemoveMemberListResponse;
// service.Update(MyList);
}
}
catch (Exception ex)
{
log.WriteLog(ex.Message);
}
}
}
aren't you erasing your values for AddMemberRequest.MemberIds after you set it?
EDIT:
Ok, I think I found it this time. Your public InArgument<bool> inserimento { get; set; } is likely the culprit.
In this case, your Workflow activity expects this to be defined upstream of the call to this Workflow. It's very likely statically set and never changed for both the Insert and Remove instances. If this is true, then it's being essentially hard coded for the Insert case, which makes the else if (!insert && action) evaluate to True for Remove and the if (insert && !action) evaluate to False for the Insert.
Since the code does work for Remove, it's reasonable to assume the bool action is working; therefore, I would start by looking into the other bool variable.
Let me know if I've missed it. (or if I'm right, I wouldn't mind the green check mark.)

Orchard CMS - new properties not updating after migration

I am writing a custom module that retrieves and pushes data directly from the Orchard DB using an injected IRepository.
This works fine until i need to update a content part. I add an update in my migrations class and the update runs through (DB schema updated with default values), however I can't update any of the new values through IRepository. I have to drop down into the NHibernate.ISession to flush the changes through.
This all works fine on a newly created recipe, it's only when i alter a part. Here are the key code snippets:
public class TranslationsPartRecord : ContentPartRecord
{
internal const string DefaultProductName = "Product";
public TranslationsPartRecord()
{
ProductName = DefaultProductName;
}
public virtual string ProductName { get; set; }
}
public class TranslationsPart : ContentPart<TranslationsPartRecord>
{
public string ProductName
{
get { return Record.ProductName; }
set { Record.ProductName = value; }
}
}
public class TranslationsHandler : ContentHandler
{
public TranslationsHandler(IRepository<TranslationsPartRecord> repository)
{
Filters.Add(StorageFilter.For(repository));
}
}
public class Migrations : DataMigrationImpl
{
public int Create()
{
SchemaBuilder.CreateTable("TranslationsPartRecord", table => table
.Column<int>("Id", column => column.PrimaryKey().Identity())
.Column("ProductName", DbType.String, column => column.NotNull().WithDefault(TranslationsPartRecord.DefaultProductName))
);
return 1;
}
public int UpdateFrom1()
{
SchemaBuilder.AlterTable("TranslationsPartRecord", table => table.AddColumn("ProductDescription", DbType.String, column => column.NotNull().WithDefault(TranslationsPartRecord.DefaultProductDescription)));
return 2;
}
}
When i add the second property "ProductDescription" in this example, after the update is run the columns appear in the DB but i cannot update them until i recreate the Orchard recipe (blat App_Data and start again).
here's how I am trying to update:
// ctor
public AdminController(IRepository<TranslationsPartRecord> translationsRepository)
{
_translationsRepository = translationsRepository;
}
[HttpPost]
public ActionResult Translations(TranslationsViewModel translationsViewModel)
{
var translations = _translationsRepository.Table.SingleOrDefault();
translations.ProductName = translationsViewModel.ProductName;
translations.ProductDescription = translationsViewModel.ProductDescription;
_translationsRepository.Update(translations);
_translationsRepository.Flush();
}
and here's the NHibernate "fix":
var session = _sessionLocator.For(typeof(TranslationsPartRecord));
var translations = _translationsRepository.Table.SingleOrDefault();
// is translations.Id always 1?
var dbTranslations = session.Get<TranslationsPartRecord>(translations.Id);
dbTranslations.ProductName = translationsViewModel.ProductName;
dbTranslations.ProductDescription = translationsViewModel.ProductDescription;
session.Update(dbTranslations);
session.Flush();
which seems a bit kludgey...
Cheers.
ps i'm still running Orchard 1.3.9
pps after more testing, the NHibernate fix has stopped working now, so perhaps my initial findings were a red herring. It seems as though new properties on the content part are totally ignored by NHibernate when updating/retrieving - as though the object definition is cached somewhere...
If your mappings aren't being updated that is strange. You can try to force it by deleting the mappings.bin in the app_data folder, and restarting the application. Orchard should recreate the nhibernate mappings and save as mappings.bin.
I have ran into the same issue, and the only way around it that I can find is to delete mappings.bin (I don't need to disable and re-enable the module). In fact, this is the answer that I got from Bertrand when I asked why this was happening.
I have logged this as an issue at http://orchard.codeplex.com/workitem/19306. If you could vote this up, then we may get it looked at quicker.
This seems like a similar issue to what I am seeing... I am seeing that when you enable a module, it runs the NHibernate mappings BEFORE running the Migrations..
https://orchard.codeplex.com/workitem/19603
Josh
Update the hash value in the ComputingHash method in the PersistenceConfiguration Class,
updating the hash value may recreate the mappings.bin file.
public class PersistenceConfiguration : ISessionConfigurationEvents
{
public void Created(FluentConfiguration cfg, AutoPersistenceModel defaultModel)
{
DoModelMapping(cfg, defaultModel);
}
public void ComputingHash(Hash hash)
{
hash.AddString("Some_strings_to_update_hash");
}
private void DoModelMapping(FluentConfiguration cfg, AutoPersistenceModel defaultModel)
{
// mappings here....
}
public void Prepared(FluentConfiguration cfg) { }
public void Building(Configuration cfg) { }
public void Finished(Configuration cfg) { }
}

How do I prevent duplicate entries using the UnitOfWork pattern with code first Entity Framework?

I am using the Unit of Work and Generic Repository pattern. Here is the statement that checks for a duplicate entry:
int id = int.Parse(beer.id); //id comes from the item we're hoping to insert
if (_unitOfWork.BeerRepository.GetByID(id) == null)
\\create a new model br
_unitOfWork.BeerRepository.Insert(br);
_unitOfWork.save();
Apparently this is failing to check to see if the beer is already in the database because I get this inner exception:
Violation of PRIMARY KEY constraint 'PK_Beers_3214EC2703317E3D'.
Cannot insert duplicate key in object 'dbo.Beers'.\r\nThe statement
has been terminated.
I also get this message:
An error occurred while saving entities that do not expose foreign
key properties for their relationships. The EntityEntries property
will return null because a single entity cannot be identified as the
source of the exception. Handling of exceptions while saving can be
made easier by exposing foreign key properties in your entity types.
See the InnerException for details.
The UnitOfWork class has my BeerRecommenderContext which implements DbContext and the UnitOfWork has a generic repository for each entity:
namespace BeerRecommender.Models
{
public class GenericRepository<TEntity> where TEntity : class
{
internal BeerRecommenderContext context;
internal DbSet<TEntity> dbSet;
public GenericRepository(BeerRecommenderContext context)
{
this.context = context;
this.dbSet = context.Set<TEntity>();
}
public virtual IEnumerable<TEntity> Get(
Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
string includeProperties = "")
{
IQueryable<TEntity> query = dbSet;
if (filter != null)
{
query = query.Where(filter);
}
foreach (var includeProperty in includeProperties.Split
(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
if (orderBy != null)
{
return orderBy(query).ToList();
}
else
{
return query.ToList();
}
}
public virtual TEntity GetByID(object id)
{
return dbSet.Find(id);
}
public virtual void Insert(TEntity entity)
{
dbSet.Add(entity);
}
public virtual void Delete(object id)
{
TEntity entityToDelete = dbSet.Find(id);
Delete(entityToDelete);
}
public virtual void Delete(TEntity entityToDelete)
{
if (context.Entry(entityToDelete).State == EntityState.Detached)
{
dbSet.Attach(entityToDelete);
}
dbSet.Remove(entityToDelete);
}
public virtual void Update(TEntity entityToUpdate)
{
dbSet.Attach(entityToUpdate);
context.Entry(entityToUpdate).State = EntityState.Modified;
}
}
}
I have a similar usage of repository using code-first. Occasionally, I would see conflicts like the one you described. My issue was with change tracking across multiple processes. Are you inserting items into the database inside one process (using a single entity context)?
If you are, you should look at the Merge Options available with Entity Framework. If you are using the default merge option (AppendOnly), then you could be querying the in memory context instead of going to the database. This could cause the behaviour you are describing.
Unfortunately, as far as I understand, all the merge options are not yet exposed to Code-First. You can choose the default (AppendOnly) or NoTracking, which will go to the database every time.
Hope this helps,
Davin

how to test a failed moq

I have used a happy test to create a method and now i am using a null test on it.
I need to change the assert in the test method but i have no clue how to go about it. i did some searches but i can seem to only find happy path tests or returns in the main method. is there a way to do a moq and test for not excecuting or is the only way having the method return a variable (a Boolean in this case)
the method
public void Upload(Data.RPADataEntity RPADataEntity)
{
if (RPADataEntity != null)
{
//Give RPA the first status and then insert it into the database it.
RPADataEntity.RPAStatusID = Convert.ToInt32(Enum.RPAStatusEnum.RPAStatus.FileInputDataUploaded);
_IRPADataLayer.InsertRpaData(RPADataEntity);
}
}
the test method
[TestMethod]
public void TestUploadRPAEntityNull()
{
//Arange
var fileinputtest = new FileInput();
RPADataEntity RPADataEntity = null;
//Act
fileinputtest.Upload(RPADataEntity);
//Assert
_mockRepository.Verify(x => x.InsertRpaData(RPADataEntity));
}
This should do it:
_mockRepository.Verify(x => x.InsertRpaData(RPADataEntity), Times.Never());

Loading an object from a db4o database

I am developing an e-commerce website that utilises db4o as the backend. All was well until last week when I came across a problem that I have been unable to solve. The code below is quite straight forward. I open a database file, save an object and then try to retrieve it. However I get nothing back. The "users" variable has a count of zero.
public class Program
{
private static string _connectionString = string.Format(#"c:\aaarrrr.db4o");
static void Main(string[] args)
{
TestUser container = new TestUser() { id = 1, Name = "Mohammad", Surname = "Rafiq" };
Db4oFactory.Configure().Diagnostic().AddListener(new DiagnosticToConsole());
using (var dbc = Db4oFactory.OpenFile(_connectionString))
{
dbc.Store(container);
}
IList<TestUser> users = null;
using (var dbc = Db4oFactory.OpenFile(_connectionString))
{
users = dbc.Query<TestUser>(x => x.id == 1).ToList();
}
if (users.Count > 0)
{
Console.WriteLine("{0} {1} with id of {2}", users.First().Name, users.First().Surname, users.First().id);
}
else
{
Console.WriteLine("\nNo data returned.");
}
Console.ReadLine();
}
}
public class TestUser
{
[Indexed]
private int _id = 0;
private string _name = string.Empty;
private string _surname = string.Empty;
public int id { get { return _id; } set { _id = value; } }
public string Name { get { return _name; } set { _name = value; } }
public string Surname { get { return _surname; } set { _surname = value; } }
}
I have attached db4o diagnostic listener and I see nothing in the console output. Everything seems fine. I know I am writing to the file because I can see the file size increase and the timestamp is also updated. I have checked all the project settings and they are all set to default. I am using .net 4, visual studio 2010 beta and windows 7. I have done some reading regarding reflection permission but I cant see how this applies here. Any help or ideas would be knidly appreciated.
After calling store(), you need to commit() before leaving the using{} statement. You closed your database before committing your changes.

Resources