Entity framework 4.1: a very special relationship - vb.net

I have in my database a table (AccessControl) that describes a sort of users "access control list" for the informations contained in the table Customers and other tables.
Example: the entity CUSTOMER is marked by the EntityId #1. If a user belongs to the department #6, he can access the records of customer #16 and #31, but he can't for #14, that can viewed by user in department #3:
Table ACCESSCONTROL:
EntityId PrimaryKey DepartmentId
1 16 6
1 31 6
1 14 3
Here an example of the classes I am using in the domain:
Public Class Customer
Public Property Id As Integer
.......
Public Overridable Property Acl As ICollection(Of AccessControl)
End Class
Public Class AccessControl
Public Property EntityId As Integer
Public Property PrimaryKey As Integer
Public Property DepartmentId As Integer
End Class
How can I describe this relationship into the DbContext definition using a fluent Code First approach?
Thank you in advance.

If I understand your problem correctly it is not possible to setup this relation in EF. There are many reasons why it will not work but the base is: unless you are able to set this relation in DB you cannot set it in EF as well. Your relation is data driven and EF has very limited support for data driven mapping - for example TPH inheritance which will not work in your scenario.

Related

How do I use Data Anotations to create a relationship between these tables?

My question is how do I create a relationship between two tables that have nonstandard column names using data anotations?
My business object is a "Rule". Each Rule has an optional "Client".
Diagram above shows PK and FK.
Here's what I tried - I didn't get any errors but I'm not seeing the Client properties in my app.
Imports System.ComponentModel.DataAnnotations
Imports System.ComponentModel.DataAnnotations.Schema
Partial Public Class Rule
<Key>
Public Property FWAClientHandling As Integer 'PK
<ForeignKey("Client")>
Public Property iClientID As Integer 'FK
Public Property Client As Client 'Child object
End Class

Change column name for non-primitive field (navigation) with EF Core

Given the following classes:
public class Mission
{
private MissionCard _missionCard;
}
public class MissionCard
{
}
I would like to create this relationship via Fluent API so that _missionCard is treated as a relationship and can be populated from DB but isn't available as a property on my Mission model.
I can create that relationship with:
modelBuilder.Entity<Mission>().HasOne<MissionCard>("_missionCard");
but by default this creates a FK column named "_missionCard". The docs show that a custom name can be specified when using .Property("property name").FromField("field name") but you cannot use .Property for non-primitive types.
Is it possible to change the column name for a relationship like above?
Managed to resolve this by inverting the relationship:
modelBuilder.Entity<MissionCard>()
.HasMany<Mission>()
.WithOne("_missionCard")
.HasForeignKey(nameof(MissionCard));

Setting One-One Relationship in DB-First Approach?

I have a table structure as follows
FeedbackTable
Id
Name
...
...
ApprovalTable
Id
FeedbackId
...
...
FeedbackTable and ApprovalTable is having 1-1 relation.When i generated Model (using Database First Approach) Feedback model is having icollection of Approval Table.I need to change to 1-1 relation with navigation in the actual model class.
How can I do it?
Is it possible to set 1-1 relation from the database itself before creating model?
StudentFeedback Model
public partial class StudentFeedback
{
public StudentFeedback()
{
this.StudentProjectApprovals = new HashSet<StudentProjectApproval>();
}
...
...
...
public virtual Icollection<StudentProjectApproval> StudentProjectApprovals { get; set; }
}
The problem you have is that the schema you are providing to DB-First doesn't express a 1-1 relationship, it is a 1-N relationship, hence EF will treat as such.
How can I do it?
By making FeedbackId both a foreign key and a primary key. You will also need to remove the Id column from the ApprovalTable table

EF Table with multiple references to same Table

I have a Database First Entity Framework Model
Tables:
1) User
Id
2) Article:
Id
UserCreated > Ref to User last edited User
UserChanged > Ref to User which created the Article
Enity Framework is Generating a Model like this
Partial Public Class Article
Public Property ID As Integer
Public Property UserCreated As Integer
Public Property UserChanged As Integer
Public Overridable Property User As User
Public Overridable Property User1 As User
End Class
Now I have another table like Vouchers also with UserCreated and UserChanged but names User1 and User.
Is there any way to specific the name of the property without changing the class itself because its generated from the Database.
You can use a DataAnnotation on the UserCreated property to specify the foreign key name:
[ForeignKey("UserCreated")]
http://msdn.microsoft.com/en-gb/data/gg193958.aspx
You can easily change the property name for User1 to any other name using the edmx-Designer.
But you should be aware that User is the reference to the column UserCreated. Because it may be that User references to UserChanged. You should check that. The best way is to check the name of the relationship. Therefore you need to give the relationship a meaningful name that you are able to distinguish them. Then you can right click on the relationship line and retrieve the relationship name.

Entity Framework 4.2 table per hierarchy group by discriminator

I am working on a project using an EF 4.2 code first model. This model contains a TPH inheritance structure for products. I need to group the polymorphic results of this inheritance model on the discriminator and am running into some issues.
The entity framework does not expose the discriminator to complete this grouping. My first question is can I get direct access to this discriminator? My reading and experience is telling me no, so I came up with this solution that sort of works. It is not performing well and I am not happy with how it will need to be maintained.
My classes look something like this (simplified):
Public MustInherit Class Product
<key()>
Public Property ProductID as integer
<StringLength(50, ErrorMessage:="Max 50 characters")>
<Required(ErrorMessage:="Product name is required")>
Public Property Name as String
<TimeStamp()>
Public Property Time_Stamp as DateTime = DateTime.Now()
End Class
Public Class Desktop
Inherits Product
<StringLength(50, ErrorMessage:="Max 50 characters")>
<Required(ErrorMessage:="Processor is required")>
Public Property Processor as String
End Class
Public Class Monitor
Inherits Product
<Required(ErrorMessage:="Monitor size is required")>
Public Property Size_Inches as Integer
End Class
I built an extension method that takes a product and returns it's basetype name as a string.
<Extension()>
Public Function ProductType(ByVal inProduct as Product) as String
ProductType = inProduct.GetType().BaseType.Name
End Function
With that, I built this structure to group the results of product by type so I can run through them:
Dim tmpProducts = db.Products.ToList()
Dim GrpProducts = tmpProducts.GroupBy(Function(prod) prod.ProductType) _
.Select(Function(s) New With {.ProductType = S.Key,
.Products = S })
I can now loop through the list to get the behavior I want, but the performance is not ideal and I am concerned it will be unacceptable as the number of products grows.
For Each ProductGroup in GrpProducts
Dim TypeName as String = ProductGroup.ProductType
Dim TypeProducts = ProductGroup.Products
Next
Also, this can give me easy access to shared properties (Name) but now I don't have many options to cast these into their real type, maybe a select case around TypeName. . .
Any recommendations are appreciated, also please forgive any code errors above, I retyped the examples from memory as I don't have access to the project at the moment.
A solution would be to model a bit more, and have a new entity ProductType having a property Name. Then you would have a simple 1-N relationship between Product and ProductType. I have not used EntityFramework, but with NHibernate you could easily make the framework always join that table on queries, so that it would not return a proxy for ProductType for each Product, which could harm performance.
As an add-on, in the future ProductType could develop other interesting properties (such as values that are common for every Product of that ProductType), so it adds flexibility to your solution, although it does have the immediate cost of adding another table to your database.
Following Linq query should get you a way to solve group by discriminator
from a in db.Records
group a.ID by new
{
Name= a is Audio ? "Audio" :
a is Video ? "Video" :
a is Picture ? "Picture" :
a is Document ? "Document" : "File"
} into g
select new
{
Name = g.Key.Name,
Total = g.Count()
}