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.
Related
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));
and totally confused now .
i am using Database First approach for developing an application
my code have models generated by ER from Table/DB
and i have created modelview for each respective models.
i have to show some "applications" name in Dropdownlist via DB
and user have to insert respective "environment" name using a textbox and dropdown, auto populated on UI .
i have 2 viewmodel class "app_details and env_details:.
app_details have public properties
appID(identity), Appname
and env_details have
appID (fk), Envid(identity),envname.
i have done with adding the application name and have a SP to getappname and id
i am confused where to add
public IEnumerable Appdetail { get; set; }
without getting model state not valid
i want to bind my model to view. how to approach PLS
Simply You can create a Select list with the appropriate item key and value and Bind that with drop down by passing to helper.
I'm getting the above error when creating a new record. I don't want to insert the identity -- the database has it auto generated and that is great.
Here is the exact exception:
[System.Data.UpdateException]
{"An error occurred while updating the entries. See the inner exception for details."}
{"Cannot insert explicit value for identity column in table 'PartRevisions' when IDENTITY_INSERT is set to OFF."}
Here are the mappings:
Public Class PartContext
Inherits DbContext
Public Property Parts As DbSet(Of Part)
Public Property PartRevisions As DbSet(Of PartRevision)
Protected Overrides Sub OnModelCreating(modelBuilder As DbModelBuilder)
MyBase.OnModelCreating(modelBuilder)
modelBuilder.Entity(Of PartRevision)().HasKey(Function(r) r.Id).Property(Function(r) r.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
End Sub
End Class
<Table("Parts")>
Public Class Part
<Key(), DatabaseGenerated(DatabaseGeneratedOption.Identity)>
Public Property Id As Integer
Public Property PartNumber As String
Public Property Owner As String
End Class
<Table("PartRevisions")>
Public Class PartRevision
Inherits Part
Public Property OriginalId As Integer
Public Property RevisionDate As DateTime
Public Property RevisionNumber As Integer
Public Property RevisionBy As String
End Class
If I don't use inheritance it works fine. If I make Id overridable and also specify the attributes on the sub class it still doesn't work.
I'm doing the OnModelCreating stuff just because I'm trying to get it to work. I feel like it should work without this. Of course it doesn't even work with this...
The following query works fine when I execute it in SQL Management Studio:
insert into PartRevisions (originalid, revisiondate, revisionnumber, revisionby, partnumber, owner)
values (1, '1/1/2013', 1, 'eep', '123', 'ME')
Here is a gist with the full program. I was trying this out in a test project because I assumed I'd run into some issues doing inheritance in EF (never done yet).
https://gist.github.com/eyston/4956444
Thanks!
The PartRevisions table must not have the Id column set as an autogenerated identity, only the table Parts for the base type. The two tables have shared primary keys. EF joins the two tables when it queries a PartRevision and it inserts rows into both tables if a PartRevision entity is inserted. Because both rows must have the same Id only one can be an identity.
Either remove the auto identity property from the "Id" column. Or alternatively you can use in your Query/Stored procedure. This will enable to to enter explicit Id values into your table even if auto identity on column is set. (Though not a good idea to use always but its good for fixes)
SET IDENTITY_INSERT dbo.YourTableName ON;
GO
Then after each table's inserts:
SET IDENTITY_INSERT dbo.YourTableName OFF;
GO
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.
I have a database with a ProbateCases table and a Properties table. The Properties table has a foreign key to the ProbateCases table called ProbateCaseId, so the relationship between ProbateCases and Properties is one-to-many.
My domain layer has a ProbateCase class and a Property class. The ProbateCase class has a collection of Properties defined as follows:
private IList<Property> _properties = new List<Property>();
public virtual IEnumerable<Property> Properties { get { return _properties; } }
public virtual Property AddProperty()
{
Property property = new Property();
_properties.Add(property);
return property;
}
The corresponding part of the Fluent NHibernate mapping looks like this:
HasMany(x => x.Properties).Where("Deleted = 0").KeyColumn("ProbateCaseId").Cascade.All().Access.CamelCaseField(Prefix.Underscore);
Note that the association is unidirectional - the ProbateCase class has a collection of Properties, but the Property class does not have a ProbateCase member.
I'm finding that querying works fine - NHibernate is creating the appropriate SQL to get Properties with the appropriate ProbateCaseId value.
However, when I save a ProbateCase to which I have added a new Property, the INSERT SQL does NOT contain a value for the foreign key field - so I get a SQL Exception complaining of a NULL value in the foreign key:
INSERT INTO AdminOverview.Properties (PropertyName) VALUES ('Name of property') -- Where the hell is the ProbateCaseId field value???
Should I be expecting NHibernate to populate the foreign key value itself, or is there something else I should be doing?
From http://nhibernate.info/doc/nh/en/index.html#collections-onetomany:
Very Important Note: If the column of a association is declared NOT NULL, NHibernate may cause constraint violations when it creates or updates the association. To prevent this problem, you must use a bidirectional association with the many valued end (the set or bag) marked as inverse="true". See the discussion of bidirectional associations later in this chapter.