When creating a View based on a PIVOT query all the view fields become NULLABLE in the view metadata, is there any way to make them NOT NULLABLE?
I'm using the NVL function in the pivoted fields I need to be NOT NULL but they still become NULLABLE.
This is a problem to me because I'm using MS Entity Framework and it won't update the model based on tables or views without NOT NULLABLE columns.
#Miguel, I don't know the "MS Entity Framework" but the name makes it sound like a framework that is oriented towards editing data. 'Entity' is typically used for structuring a cache of database data in preparation for changing and updating that data back into the database. This does not seem like what you want to do.
Re-reading this question I believe that you have some sort of pivot generator you are using to create the view on-the-fly for the user. For this reason you do not intend to revise the Entity Model. I don't think you need an entity model at all.
An Entity Framework is likely to be looking for NOT NULL columns in order to find a 'primary key' or other row-level identifier that it can use. Why does it want these?
provide a key usable to update any row
provide key for paginating the result set
provide a key to support in-memory filtering of the result set
support dynamic sorting operations on the result set
I also surmise you have some sort of UI control that presents 'Entity' collections very nicely and so you want to use that control.
The control may not need an 'Entity' - check to see what its interface is. Perhaps there is a superclass of Entity or an interface that you can generate rather than an updateable Entity. If you can do that, you should be able to present it in the spiffy UI control and not hit the wall with your NULLABLE columns.
One of possible solutions is generating a new table on the fly based on results of query and tuning constraints for this table after that.
I don't like this method for too many dynamic SQL :)
Another solution is a prebuilt materialized view.
Look here (Oracle docs) for "ON PREBUILT TABLE Clause".
You need to update your model in Visual Studio (VS). Because this doesn't know what type information is in every column. Then you have to specify in the query of pivot table the data type. For example, Use to_number for specify a explicit conversion. When you going to update the model in VS you must based in for example materialized view (with explicitly defined data types). Please create Materialized view with explicitly defined data types based in the pivot table (this have to contain not only nvl function else defined data types, string, number, etc ) and then Update your model.
Only Materialized view? No, it can be a table (but is troublesome). Can be It direct of the pivot table? Does not always work (as in your case). Important Is to have defined data types.
You could use code-first if you don't have to many of these views, Scott Gu has a good article "Code first with existing database" that shows how to do this.
This might entail having 2 ways to access the db, which may or may not work for you.
Related
I want to persist a linked list of objects using in my ASP.Net Core application. For simplicity, I'll use blog and comments; although the real context is much more complex.
I scaffolded two tables, and changed ICollection<Comment> to LinkedList<Comment>. However, if I create an initial migration and apply to an empty database, I don't get anything "linked" in the database (no next or previous). Also, if I seed the data, and then do something like this:
var comments = _context.blogs.First().Comments
I get null. If I leave public virtual ICollection<Comment> Comments, I get the IEnumerable just fine.
I tried to use LinkedList<LinkedListNode<Comment>> instead, and it works nice unless I try to create a migration. Getting an error
No suitable constructor found for entity type 'LinkedListNode'. The following constructors had parameters that could not be bound to properties of the entity type: cannot bind 'value' in 'LinkedListNode(Comment value)'; cannot bind 'list', 'value' in 'LinkedListNode(LinkedList list, Comment value)'.
I couldn't find any guidance how to implement LinkedList in C#/.NET Core (obviously, I can do it manually, having next and prev fields - but I would very much prefer to use framework capabilities, if possible!)
I don't know much about MS SQL server, but the whole next and prev parts in mysql won't work because you can't map the keys it would require to track the fields properly because each link has to have an id in a database to link to. only thing I know of would be create the next/prev yourself and use some custom data persistence or data annotations. but the foreign key constraints I'm pretty sure on any relational database will prevent you from auto persisting those types of fields. reason being tracking deletes, inserts etc would be a nightmare because if you remove the middle of the chain, then the database has to try and guess where to link the ends to
I have more than 50 data tables that have nearly identical structures. Some of the tables have additional columns. I'm developing an application to help me monitor and track changes to the data contained in these tables and only need to be able to read the data contained in them. I want to create an entity framework model that will work with all of the tables and give me access to all columns that exist.
As long as the model contains the subset of columns that exist is all of the tables my model works and I can dynamically switch between the tables with the same model. However I need accesses to the additional columns when they exist. When my model contains a column that doesn't exist in the table that I switch to I get an exception for an invalid column. Is there a way to have my model be the set of all columns and if the column doesn't exist in the context of a particular table handle it in a way that I still have access to the columns that exist? I know that using strait SQL I can do this quite easily but I'm curious is there is a way to do this with entity framework. Essentially I am looking for the equivalent of querying sys.columns to determine the structure of the table and then interact with the table based on knowing what columns exist from the sys.columns query.
Sample of issue:
The 50+ tables hold data from different counties. Some of there counties have included additional data, for instance a url link to an image or file. Thus I have an column that is a varchar that contains this link. Many of the counties don't supply this type of attribute and it isn't apart of the table in other counties. But there are 100 other reported attributes that are common between all tables. I realize a solution to this issue is to have all tables contain all possible columns. However in practice this has been hard to achieve due to frequent changes to provide more to our clients in certain counties.
From the EF prospective I do not know a solution but you can try something with an extension method like below:
public static DbRawSqlQuery<YourBaseModel> GetDataFromTable(this ApplicationDbContext context, string tableName)
{
return context.Database.SqlQuery<YourBaseModel>("select * from " + tableName);
}
I think this will map only columns that exists in table with properties in your model.
This is not tested by the way but it can give you an idea of what I mean.
Entity Framework supports generating Table per Concrete type mapping, this lets you have a base class that contains all the shared columns, and derived classes for each specific table
https://weblogs.asp.net/manavi/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-3-table-per-concrete-type-tpc-and-choosing-strategy-guidelines
I have these two related tables Client (ClientId, Name) and ClientDescription (ClientDescriptionId, (FK) ClientId, Description). That is to say each Client can have many associated descriptions. Now, when displaying the a list of ClientDescriptions, I also need to know what the Name of it's associated Client is.
Now you'll probably say that I allready have this information, since I can simply follow my navigation property back to the associated Client and use its Name. I can't do that because I'm autogenerating a grid in Ria services, and this just gives me a count for navigation properties, and I haven't found a way to flatten this down in my metadata file. Hence why I want a property.
The whole idea is that I want to be able to add a new field to my database, update my entity classes from the database and regenerate my domain service, and the new field should just pop up in my grid. I shouldn't have to update my xaml just because my database happen to have an extra field.
So, what I would like to do is add a ClientName field to the entity (clr object), but keep my database clean (no such denormalization in the db).
So, I generated my edmx, and added a new property named ClientName. Set it to StoreGeneratedPattern.Computed, and compiled. I then get a nasty little error
Error 3004: Problem in mapping fragments starting at line NN: No mapping specified for properties (etc..)
The solution apparently is to generate my database from my edmx. (Or that's what answers to questions about that error seems to yield.) But this generates an actual DB-field, which I don't want, so that answer doesn't apply to my case.
So my question is: How can I denormalize my clr entity, but keep my db tables normalized?
Edit: I guess this question can be generalized a bit. The issue would be the same if ClientDescription contained a few numeric fields that I wanted to do some calculations on, and I wanted the result available as a field and the algorithm should be in c# rather than in my database.
To answer your more generalized question:
Entities are generated by the Entity Framework with a partial keyword.
This means that the code of an entity can be split in multiple source files in the same namespace and assembly. One will contain the generated code from the Entity Framework, the other will contain custom properties and methods.
If for example, your entity has the database fields Price and Amount you could add a property in the partial class TotalPrice which would return Price * Amount.
Then the algorithm will be C# and your database won't know about the extra property.
I have a design question related to Entity Framework entities.
I have created the following entity:
public class SomeEntity {
// full review details here
}
This entity has as an example 30 columns. When I need to create a new entity this works great. I have all of the required fields in order to insert into the database.
I have a few places in my app where I need to display some tabular data with some of the fields from SomeEntity, but I don't need all 30 columns, maybe only 2 or 3 columns.
Do I create an entirely new entity that has only the fields I need (which maps to the same table as SomeEntity, but only retrieves the column I want?)
Or does it make more sense to create a domain class (like PartialEntity) and write a query like this:
var partialObjects = from e in db.SomeEntities
select new PartialEntity { Column1 = e.Column1, Column2 = e.Column2 };
I am not sure what the appropriate way to do this type of thing. Is it a bad idea to have two entities that map to the same table/columns? I would never actually need the ability to create a PartialEntity and save it to the database, because it wouldn't have all of the fields that are required.
Your first approach is not possible. EF doesn't support multiple entities mapped to the same table (except some special cases like TPH inheritance or table splitting).
The second case is common scenario. You will create view model for your UI and either project your entity to view model directly in query (it will pass from DB only columns you project) or you will query whole entity and make conversion to view model in your application code (for example by AutoMapper as #Fernando mentioned).
If you are using EDMX file for mapping (I guess you don't because you mentioned ef-code-first) you can use third approach which takes part from both mentioned approaches. That approach defines QueryView - it is EF based view on the mapped entity which behaves as a new read only entity. Generally it is reusable projection stored directly in mapping.
What you proposed as a first solution is the "View model paradigm", where you create a class for the sole purpose of being the model of a view to retrieve data and then map it to the model class. You can use AutoMapper to map the values. Here's an article on how to apply this.
You could create a generic property filter method that takes in an object instance, and you pass in a string array of column names, and this method would return a dynamic object with only the columns you want.
I think it would add unnecessary complexity to your model to add a second entity based on the same data structure. I honestly don't see the problem in having a single entity for updating\editing\viewing. If you insist on separating the access to SomeEntity, you could have a database view: i.e. SomeEntityView, and create a separate entity based on that.
I'm developing a hierarchical object model that is self-referencing as a 0/1 --> * relationship. An object without a parentID is a root element. The parentID is also the foreign key on the self-join. From my understanding, using the parentID as a foreign key will only point to a column where child elements may be found --> does this force an iteration through the entire data set for that column? Is this a scenario where a clustered index should be formed? ....would it be proper to use the XML data type to store all childrenIDs in a single field then load and reference that document for each object? It seems doing this would at least allow me to simplify my object persistence layer and give me more control over recording transactions.
Any advice?
I would strongly suggest against using XML to store the child IDs. It will cause countless headaches trying to maintain it down the road, not to mention trying to use it outside of your application (for example, from a reporting solution or for ETL).
Have you looked into the HIERARCHYID data type? It's in SQL 2008 and may be useful for you here. I don't know what kind of support the various programming languages/ODBC/OLE DB have for it, but you can convert it to a string with .ToString() and that can be manipulated pretty easily. It also then allows you to use the other methods of HIERARCHYID in T-SQL, like .GetAncestor(), etc.