Entity Framework Plus. A new entity is not returned with cache - entity-framework-plus

I use Entity Framework Plus with FromCache option with EF6.
My problem is that after adding a new item the cache that returned doesn't contain the item.
Is it possible to "update" the cache automatically after a new item added?
Save a new policy:
db.policies.Add(policy);
db.SaveChanges();
Get the all policies:
database.policies.FromCache().ToList();
EF Plus has CacheItemPolicy but I have to supply SqlCommand for the class that I do not have as you can see in the example of saving an item.

Try the option IsAutoExpireCacheEnabled for EF6
QueryCacheManager.IsAutoExpireCacheEnabled = true;
Fiddle: https://dotnetfiddle.net/3WHMGk
As soon as something is added/modified/deleted, all caches related to this DbSet will be clreared.

Related

Entity Framework Core GetOrAdd Method

I'm working on a post method that should have a really good performance.
I have a value in the request body that will look in the database for the row that is connected with that value and return it and add it as a foreign key.
So how it is now:
Look in the database and check if the data already exists
If no add it to the database
Look that added or already existing data in the database and join it to the entity
So now there are 3 calls to the database
I was wondering if there is some kind of GetOrAdd method that will connect the table to my data if it exists and if it not exists add it to the database so it will most of the time only have 1 call to the database instead of always 3 calls
Please read the following doc
Here is an "Insert or Update" pattern:
public void InsertOrUpdate(Blog blog)
{
using (var context = new BloggingContext())
{
context.Entry(blog).State = blog.BlogId == 0 ?
EntityState.Added :
EntityState.Modified;
context.SaveChanges();
}
}
Of note, once you hit SaveChanges() you can expect your in memory object (blog, in this case) to be the same object that is stored in the database, and would not have to make a 3rd call to retrieve it again. EF Core will update the Primary Key with the actual persisted Id.
using (var context = new BloggingContext())
{
var blog = new Blog {Id = 1, Url = "blablabla" };
context.Blogs.Update(blog);
await context.SaveChangesAsync();
}
If a reachable entity has its primary key value set then it will be tracked in the Microsoft.EntityFrameworkCore.EntityState.Modified state. If the primary key value is not set then it will be tracked in the Microsoft.EntityFrameworkCore.EntityState.Add state.
This comment is from Entity Framework Core's Update method. You just need to call Update method if entity is exist in Database it will be updated otherwise will be created as new record.

How to map colums in a table database in to Properties and relation with Fields

I'm studying Sensenet Framework and installed successfull on my computer, and now I'm developing our website based on this framework.I read documents on wiki and understood relationship between Database <-> Properties <--> Fields <-> View (you can see the image in this link: http://wiki.sensenet.com/Field_-_for_Developers). For suppose, if I added a new table in to Sensenet's database and desiderate show all datas inside this table to our page, but I don't know how to dev flow by this model: Database <=> Property <=> Field <=> View. ? can you show steps to help me?
Please consider storing your data in the SenseNet Content Repository instead of keeping custom tables in the database. It is much easier to work with regular content items and you will have all the feature the repo offers - e.g. indexing, permissions, and of course an existing UI. To do this, you will have to take the following steps:
Define content types in SenseNet for every entity type you have in your existing db (in the example below this is the Car type).
Create a container in the Content Repository where you want to put your content (in this case this is a Cars custom list under the default site).
Create a command line tool using the SenseNet Client library to migrate your existing data to the Content Repository.
To see the example in detail, please check out this article:
How to migrate an existing database to the Content Repository
The core of the example is really a few lines of code that actually saves content items into the Content Repository (through the REST API):
using (var conn = new SqlConnection(ConnectionString))
{
await conn.OpenAsync();
using (var command = new SqlCommand("SELECT * FROM Cars", conn))
{
using (var reader = await command.ExecuteReaderAsync())
{
while (await reader.ReadAsync())
{
var id = reader.GetInt32(0);
var make = reader.GetString(1);
var model = reader.GetString(2);
var price = reader.GetInt32(3);
// Build a new content in memory and fill custom metadata fields. No need to create
// strongly typed objects here as the client Content is a dynamic type.
// Parent path is a Content Repository path, e.g. "/Root/Sites/Default_Site/Cars"
dynamic car = Content.CreateNew(ParentPath, "Car", "Car-" + id);
car.Make = make;
car.Model = model;
car.Price = price;
// save it through the HTTP REST API
await car.SaveAsync();
Console.WriteLine("Car-" + id + " saved.");
}
}
}
}

Adding a new attribute to an Object Class and Expecting it to automatically show up in existing objects in Apache DS

I am working on a use case where I have to dynamically add a new attribute to an existing object class in Apache DS.
1)Here is some code which defines my object class:--
Attributes attrs = new BasicAttributes(true);
attrs.put("NUMERICOID", "1.3.6.1.4.1.18060.0.4.3.3.1");
attrs.put("NAME", "ship");
attrs.put("DESC", "An entry which represents a ship");
attrs.put("SUP", "top");
attrs.put("STRUCTURAL", "true");
Attribute must = new BasicAttribute("MUST");
must.add("cn");
attrs.put(must);
Attribute may = new BasicAttribute("MAY");
may.add("numberOfGuns");
may.add("numberOfGuns2");
may.add("description");
attrs.put(may);
//add
schema.createSubcontext("ClassDefinition/ship", attrs);
2) Adding an object of that object class:
Attributes attributes=new BasicAttributes();
Attribute objectClass=new BasicAttribute("objectClass");
objectClass.add("ship");
attributes.put(objectClass);
Attribute g=new BasicAttribute("numberOfGuns");
Attribute g2=new BasicAttribute("numberOfGuns2");
Attribute cn=new BasicAttribute("cn");
g.add("2");
g2.add("3");
cn.add("four");
attributes.put(g);
attributes.put(cn);
attributes.put(g2);
;
ctx.createSubcontext("cn=four,dc=example,dc=com",attributes);
3) Add a new attribute -- 'mustA' to the object class
Attributes attrs = new BasicAttributes(true);
attrs.put("NUMERICOID", "1.3.6.1.4.1.18060.0.4.3.3.1");
attrs.put("NAME", "ship");
attrs.put("DESC", "An entry which represents a ship");
attrs.put("SUP", "top");
attrs.put("STRUCTURAL", "true");
Attribute must = new BasicAttribute("MUST");
must.add("cn");
must.add("mustA");
attrs.put(must);
Attribute may = new BasicAttribute("MAY");
may.add("numberOfGuns");
may.add("numberOfGuns2");
may.add("description");
attrs.put(may);
//modify
schema.modifyAttributes("ClassDefinition/ship",DirContext.ADD_ATTRIBUTE ,attrs);
Once the new attribute is added(which means object class is modified), If i add a new object of that object class type, I can see the newly added attribute in the newly created object.
My Question is, What happens to the objects which were created before I added the new attribute? How can I make the new attribute to show up in the exiting objects automatically? For example, here will the new attribute "mustA" automatically show up in object "four"?
Or Will I have to manually go and modify that object to add that new attribute?
You will need to update the schema. For ApacheDS the easiest method is to download Apache Studio and take a look at 2.3.1 - Adding Schema Elements
Oh, and you will always get great support from The Directory Users List for ApacheDS. The developers are very active.
AFIK, ApacheDs will support adding schema from LDAP calls, but I am not positive. (See The Directory Users List for ApacheDS)
If you insist doing this the hard way, check out the examples at:
http://docs.oracle.com/javase/jndi/tutorial/ldap/schema/object.html
-jim

validation based on attributes in metadata class

I am performing validation based on attributes in metadata.cs file. I am using Entity framework 4.0 and using wcf ria services. I want to know what is the equivalent of Page.IsValid in asp.net in silverlight? How do i ensure that the entity is in correct state before saving it? If i do not ensure this an exception fires which looks very ugly. I found a property named entityName.ValidationErrorCount so if my entity is named User i do objUser.ValidationErrorCount is less than equal to 0 i save it. Problem with this approach is if the user doesn't enter value in any of the textbox then subsequently all the values in the entity are null. So ValidationErrorCount property returns 0 because all are null values and thus my program tries to save the entity but naturally the entity is in incorrect state so exception fires. How do i get past this problem?
I hope i am clear. If not, please let me know. Thanks in advance :)
You can validate an entity using the Validator class (from the System.ComponentModel.DataAnnotations
namespace), like so (where entity is a reference to the entity to be validated):
List<ValidationResult> validationResults = new List<ValidationResult>();
ValidationContext validationContext = new ValidationContext(entity, null, null);
bool isValid = Validator.TryValidateObject(entity, validationContext, validationResults, true);
Alternatively, are you using the DataForm control? If so, there's an even easier way to check whether the current item is valid, by calling the ValidateItem() method on the DataForm. This will return a boolean indicating whether the current item is valid (you can also check the IsItemValid property of the DataForm). It will also update the bound controls to show their validation status. If you're not using the DataForm, then it will certainly make it easier if you can. Otherwise, simply add the validation results to the entity's ValidationErrors property:
foreach (ValidationResult result in validationResults)
entity.ValidationErrors.Add(result);
Hope this helps...
Chris

Persist a top-level collection?

NHibernate allows me to query a database and get an IList of objects in return. Suppose I get a list of a couple of dozen objects and modify a half-dozen or so. Does NHibernate have a way to persist changes to the collection, or do I have to persist each object as I change it?
Here's an example. Suppose I run the following code:
var hql = "from Project";
var query = session.CreateQuery(hql);
var myProjectList = query.List<Project>();
I will get back an IList that contains all projects. Now suppose I execute the following code:
var myNewProject = new Project("My New Project");
myProjectList .Add(myNewProject);
And let's say I do this several times, adding several new projects to the list. Now I'm ready to persist the changes to the collection.
I'd like to persist the changes by simply passing myProjectList to the current ISession for updating. But ISession.SaveOrUpdate() appears to take only individual objects, not collections like myProjectList. Is there a way that I can persist changes to myProjectList, or do I have to persist each new object as I create it? Thanks for your help.
David Veeneman
Foresight Systems
If you load objects like in your example - then yes you have to persist them one by one.
However, if you make a small design change, and load something like : Account that has an IList<Project> - if you specify cascade "what_cascade_you_need" in the mapping , then when you change the projects on Account , you only have to save Account and everything will get saved.