开发者

Map many to many relation in entity framework

I have a sql server database and a c# win forms application and I am using entity framework.

In the database I have the following tables :

Table Joint(
      JointID
      FirstName
      FatherName
      LastName)

Which represent a joint in gym and every joint has a closet, and every joint has one closet and each closet can be rent by one joint. so i thought this one to one relation i don't know if it's true but anyway this the closet table :

Table Closet(
   ClosetID
   Number)

but at the same time i want to keep a history for each closet because maybe someone rent it for 2 months and then someone else rent the same closet after the first one so i want to know each joint rent this closet, and i want to know who is own know and how much he payed for the rent of the closet, so i want a start time, end time, price.

at last i figured out that i want a third table between the above tables and it will be a many to many relation so i created :

Table ClosetHistory(
   JointID     fk
   ClosetID    fk
   StartTime
   EndTime
   Price)

and i think this right but i am not sure and this all not my problem. My problem is when i update my entities from database the relat开发者_如何学Pythonion between joint and closet not created and it create a joint entity stand alone and a closet entity but it doesn't contain a startTime, EndTime, Price attributes, and the ClosetHistory not created and that is true because the table between tow tables in many to many relation not represented as an entity, But if i remove the startdate and enddate, price fields from ClosetHistory table and re pdate my entities it works and the relation is created but then i can't save the starttime and endtime and price for the closets

can you help me please ??

and i am sorry for all this explanation, and i am sorry for my English language i know it's very bad :)


You can use 4 table scheme and a pair of Insert and Delete triggers to resolve your issue.

Map many to many relation in entity framework

CREATE TRIGGER [dbo].[AddTrigger]
   ON [dbo].[ClosetJoint]
   AFTER INSERT
AS 
BEGIN
    SET NOCOUNT ON;
    DECLARE @JointId INT;
    DECLARE @ClosetId INT;

    SET @ClosetId = (SELECT ClosetID FROM inserted);
    SET @JointId = (SELECT JointID FROM inserted);

    INSERT INTO ClosetHistory(ClosetID, JointID, StartTime)
     VALUES(@ClosetId, @JointId, GETDATE())
END

CREATE TRIGGER [dbo].[DeleteTrigger]
   ON [dbo].[ClosetJoint]
   AFTER Delete
AS 
BEGIN
    SET NOCOUNT ON;
    DECLARE @JointId INT;
    DECLARE @ClosetId INT;

    SET @ClosetId = (SELECT ClosetID FROM deleted);
    SET @JointId = (SELECT JointID FROM deleted);

    UPDATE ClosetHistory SET EndTime = GETDATE()
    WHERE ClosetID = @ClosetId AND JointID = @JointId AND EndTime IS NULL
END
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜